Creating a widget at runtime
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.
The GridView example from the previous chapter was created in code. But unlike the GridView recipe, in this recipe, we are going to add a view to the existing layout defined in activity_main.xml
.
Getting ready
Create a new project in Android Studio and call it RuntimeWidget
. Select the Empty Activity option when prompted for the Activity type.
How to do it...
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 the
res/layout/activity_main.xml
and add an ID attribute to the mainRelativeLayout
, as follows:android:id="@+id/layout"
- Completely...