Home » Android » Android Core » Android dynamic and XML layout

About Rakesh Cusat

Rakesh Cusat

Android dynamic and XML layout

Android activity contains various user interface components e.g Button, Radio button, List, Text field etc.

The user interface component can be arranged/attached with the activity in two different ways.

  1. Declaring UI element in layoutfile
    Basically, Layout file is xml formatted file present in res/layout. In this file, tags are used to define any UI component and properties are used to configure the components. It is similar to HTML tags. This style is preferred because UI related codes and business logic codes are separated. It is comparatively easier to manage.
  2. Creating view element at runtime
    UI Companent can be created programmatically. UI component class setter methods help to configure the component. This style is not recommended unless it’s really required. In this style, business logic gets mixed with the component UI code. It doesn’t look neat and sometimes it’s hard to manage.

In this tutorial, we will create two different Activity classes with the same UI components but with different techniques.

Create an Android project(as shown in this tutorial) and name the Activity as XMLLayoutActivity and layout file as activity_xmllayout.xml. We will define some string constants to be used in layout file and Activity. Open the file string.xml present in res/values and put the following contents:

    <string name='app_name'>AndroidLayout</string>
    <string name='menu_settings'>Settings</string>
    <string name='title_activity_xmllayout'>XMLLayoutActivity</string>
    <string name='c4r'>Code4Reference.com</string>
    <string name='OtherActivity'>Other Activity</string>
    <string name='dynamic_layout_activity'>Dynamic Layout Activity</string>

Now, we will write very simple layout file which contains Textview, EditText and Button UI components as shown below.

<LinearLayout xmlns:android='http://schemas.android.com/apk/res/android'

        android:[email protected]/padding_medium'
        android:[email protected]/c4r'
        tools:context='.XMLLayoutActivity' />
        android:[email protected]/padding_medium'
        android:[email protected]/c4r'
        android:[email protected]/padding_medium'
        android:[email protected]/OtherActivity'

Let’s define the first activity class called XMLLayoutActivity. This Activity uses the layout file defined above.

package com.code4reference.androidlayout;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class XMLLayoutActivity extends Activity {

 Button btOtherActivity;

 public void onCreate(Bundle savedInstanceState) {
  // Attaching the layout file with the current Activity.
  // Associate the Button object with the Button defined in the layout
  // file. Notice that R.id.btOtherActivity is associated with the 
  //button in activity_xmllayout.xml layoutfile.
  btOtherActivity = (Button) findViewById(R.id.btOtherActivity);
  //Attaching the OnclickListener with the button.
  btOtherActivity.setOnClickListener(new OnClickListener() {
   public void onClick(View view) {
    //Creating an Intent which will invoke
    //the other Activity (DynamicLayoutActivity).
    Intent intent = new Intent(getApplicationContext(),
    //This method will start the other activity.

Now, add another DynamicLayoutActivity class to the same package which extends Activity class.This activity class will dynamically add the UI component to Activity. Put the following content in the class definition. The embedded comments will help to understand the code.

package com.code4reference.androidlayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class DynamicLayoutActivity extends Activity {

 protected void onCreate(Bundle savedInstanceState) {
  // This will create the LinearLayout
  LinearLayout ll = new LinearLayout(this);
  // Configuring the width and height of the linear layout.
  LayoutParams llLP = new LayoutParams(
    //android:layout_width='match_parent' an in xml

  TextView tv = new TextView(this);
  LayoutParams lp = new LayoutParams(

  //android:[email protected]/c4r'
  //android:[email protected]/padding_medium'
  tv.setPadding(8, 8, 8, 8);
  EditText et = new EditText(this);
  et.setPadding(8, 8, 8, 8);
  Button bt = new Button(this);
  bt.setPadding(8, 8, 8, 8);
  //Now finally attach the Linear layout to the current Activity.

  //Attach OnClickListener to the button.
  bt.setOnClickListener(new OnClickListener() {
   public void onClick(View view) {
      'This is dynamic activity', Toast.LENGTH_LONG).show();

As you can see, the code doesn’t look that neat compared to the former one. In OnClickListener, Toast class has been used to prompt the message. Now, we need to modify the AndroidManifest file because another activity class has been added.

<manifest xmlns:android='http://schemas.android.com/apk/res/android'
    android:versionName='1.0' >
        android:targetSdkVersion='15' />
        android:[email protected]/ic_launcher'
        android:[email protected]/app_name'
        android:[email protected]/AppTheme' >
            android:[email protected]/title_activity_xmllayout' >
                <action android:name='android.intent.action.MAIN' />
                <category android:name='android.intent.category.LAUNCHER' />
        <activity android:name='.DynamicLayoutActivity'
            android:[email protected]/dynamic_layout_activity'>
            <intent-filter >
                <category android:name='android.intent.category.LAUNCHER'/>

Once the coding is done, execute the application and you will notice the following Activity on screen.

If you click the button, the next activity will appear having almost similar layout but with different title. If you click the button on the another activity, it will show you a toast message. You can get the source code from github/Code4Reference. You can read more about the android layout here.

Reference: Android dynamic and xml layout from our JCG partner Rakesh Cusat at the Code4Reference blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



One comment

  1. Do i need to create activity with title DynamicLayoutActivity or only class with title DynamicLayoutActivity ?

Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns