As mentioned before, generally, the UI is declared in XML files and then modified during runtime through the Java code. It is possible to create the UI completely in Java code, though for a complex layout, it would generally not be considered best practice.
In this recipe, we are going to add a view to the existing layout defined in activity_main.xml
.
Create a new project in Android Studio and call it RuntimeWidget
. Select the Empty Activity
option when prompted for the Activity Type
.
We will start by adding an ID attribute to the existing layout so we can access the layout in code. Once we have a reference to the layout in code, we can add new views to the existing layout. Here are the steps:
- Open
res/layout/activity_main.xml
and add an ID attribute to the rootConstraintLayout
, as follows:
android:id="@+id/layout"
- Completely remove the default
<TextView>
element. - Open the
MainActivity.java
file so we can add code to theonCreate(...