Introduction
This article explains how to dynamically create the layout in Android. Android Studio is used for the sample.
Typically we develop the layout for an Android application by creating the XML file. But in this, we will create the layout for the activity using code in the class file. In this, I have created four buttons inside a RelativeLayout that uses methods and variables to change their layout. First, you will create the Relativelayout and call LayoutParams to set the parameters as in the following:
- // Creating a new RelativeLayout
- RelativeLayout relativeLayout = new RelativeLayout(this);
- // Defining the RelativeLayout layout parameters with Fill_Parent
- RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
Now you will create the buttons that you want to show on screens as in the following:
- // Creating a new Left Button
- Button button1 = new Button(this);
- button1.setText("Button1");
- // Creating a new Left Button with Margin
- Button button2 = new Button(this);
- button2.setText("Button2");
- // Creating a new Center Button
- Button button3 = new Button(this);
- button3.setText("Button3");
- // Creating a new Bottom Button
- Button button4 = new Button(this);
- button4.setText("Button4");
Step 1

Step 2
Default XML file
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin"
- tools:context=".MainActivity">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/hello_world" />
- </RelativeLayout>
Step 3

Join the conversation! Your thoughts help the community grow.