Creating Views, Layouts Programatically

person folder_openAndroidaccess_time February 27, 2015

We already learned how to create simple widgets like TextView, Button, ImageView, LinearLayout etc. In this tutorial we are going to learn how to create these widgets programatically.
See flowing Steps :

  1. Create simple layout file with one parent view. In this example I’ve added ScrollView to accommodate newly created views.
  2. In MainActivity.java create new View
  3. Create LayoutParams and attach them to the newly created views.

Note:
All the attributes that we use in xml layout can be set programatically.
Layout height and width are mandatory for any View.

1. Manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dynamiclayouts"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name="MainActivity">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.MAIN"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Activity layout file

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >
    <LinearLayout
        android:id="@+id/rootView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="5dp" >
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Change Text" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="This TextView is declared in layout xml file" />
    </LinearLayout>
</ScrollView>

3. Main Activity code

4. Main Activity code
The code has self explanatory inline comments.

package com.example.dynamiclayouts;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
	private TextView txtView1;
	private Button btn1;
	private LinearLayout rootView;
	private int count;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		rootView = (LinearLayout) findViewById(R.id.rootView);
		txtView1 = (TextView) findViewById(R.id.textView1);
		btn1 = (Button) findViewById(R.id.button1);
		// Add onclick listener to the button
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Change the some attributes of the textview
				txtView1.setText("The text is changed. Note also the \n \"background\", \n\"font size\", \n\"text color\"");
				txtView1.setBackgroundColor(Color.GREEN);
				txtView1.setTextColor(Color.RED);
				txtView1.setTextSize(16);
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Add menu to the actionbar
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
		case R.id.item1:
			addNewButton();
			break;
		default:
				break;
		}
		return true;
	}
	/**
	 * Add new button and attach it to the root view
	 */
	private void addNewButton() {
		//Create new linearlayout
		LinearLayout ll = new LinearLayout(this);
		// Create layoutparams
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// Set the layout params to the linearlayout
		ll.setLayoutParams(params);
		//Create new button widget
		Button btn = new Button(this);
		//Set layout params to the button
		btn.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		btn.setText("Dynamic Button "+count++);
		//Add the button to the newly created linearlayout
		ll.addView(btn);
		// Now attach the linearlayout to the root view
		rootView.addView(ll);
	}
}

5. Demonstration

Dynamic Layouts XML Widgets
Dynamic Layouts XML Widgets

Views created Programatically

Views created dynamically
Views created dynamically

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">