Blog Archive

Android programmatically add views - Button, TextView, EditText, RadioButton, CheckBox, ToggleButton

Sometimes there is need for dynamically generating screen layout based on data from SQLITE database tables, such as question answer forms, etc. Also you can use this along with static XML layouts to design more User friendly application. Depending on the application need, you can choose a mixture of static XML, inflating XML views using code and generating views directly using Java code in an Activity. In this tutorial we will learn how to programmatically add the following views using Java Code in an Android Activity
  1. Button
  2. TextView
  3. EditText
  4. RadioButton
  5. CheckBox
  6. ToggleButton

Here is a sample code to help you get started

package com.as400samplecode;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.LinearLayout.LayoutParams;

public class DynamicLayoutActivity extends Activity implements OnClickListener{
    private static final int MY_BUTTON = 9000;
    public void onCreate(Bundle savedInstanceState) {

        LinearLayout ll = (LinearLayout)findViewById(;

        // add text view
        TextView tv = new TextView(this);
        tv.setText("Dynamic Text!");

        // add edit text
        EditText et = new EditText(this);
        et.setText("Dynamic EditText!");

        // add button
        Button b = new Button(this);
        b.setText("Button added dynamically!");
        b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        //add checkboxes
        for(int i = 0; i < 10; i++) {
            CheckBox cb = new CheckBox(this);
            cb.setText("Dynamic Checkbox " + i);

        //add radio buttons
        final RadioButton[] rb = new RadioButton[5];
        RadioGroup rg = new RadioGroup(this); //create the RadioGroup
        rg.setOrientation(RadioGroup.HORIZONTAL);//or RadioGroup.VERTICAL
        for(int i=0; i<5; i++){
            rb[i]  = new RadioButton(this);
            rb[i].setText("Dynamic Radio Button " + i);
            rg.addView(rb[i]); //the RadioButtons are added to the radioGroup instead of the layout

        ll.addView(rg);//you add the whole RadioGroup to the layout
        // add Toggle button
        ToggleButton tb = new ToggleButton(this);
        tb.setTextOn("Dynamic Toggle Button - ON");
        tb.setTextOff("Dynamic Toggle Button - OFF");
        tb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

    public void onClick(View v) {
        Toast toast;
        Log.w("ANDROID DYNAMIC VIEWS:", "View Id: " + v.getId());
        switch (v.getId()) {
        case MY_BUTTON:
            toast = Toast.makeText(this, "Clicked on my dynamically added button!", Toast.LENGTH_LONG);
            toast.setGravity(Gravity.TOP, 25, 400);
            // More buttons go here (if any) ...

    public void saveAnswers() {
        LinearLayout root = (LinearLayout) findViewById(; //or whatever your root control is

    private void loopQuestions(ViewGroup parent) {
        for(int i = 0; i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if(child instanceof RadioGroup ) {
                //Support for RadioGroups
                RadioGroup radio = (RadioGroup)child;
                storeAnswer(radio.getId(), radio.getCheckedRadioButtonId());
            else if(child instanceof CheckBox) {
                //Support for Checkboxes
                CheckBox cb = (CheckBox)child;
                int answer = cb.isChecked() ? 1 : 0;
                storeAnswer(cb.getId(), answer);
            else if(child instanceof EditText) {
                //Support for EditText
                EditText et = (EditText)child;
                Log.w("ANDROID DYNAMIC VIEWS:", "EdiText: " + et.getText());
            else if(child instanceof ToggleButton) {
                //Support for ToggleButton
                ToggleButton tb = (ToggleButton)child;
                Log.w("ANDROID DYNAMIC VIEWS:", "Toggle: " + tb.getText());
            else {
                //Support for other controls

            if(child instanceof ViewGroup) {
                //Nested Q&A
                ViewGroup group = (ViewGroup)child;

    private void storeAnswer(int question, int answer) {
        Log.w("ANDROID DYNAMIC VIEWS:", "Question: " + String.valueOf(question) + " * "+ "Answer: " + String.valueOf(answer) );
        Toast toast = Toast.makeText(this, String.valueOf(question) + " * "+ "Answer: " + String.valueOf(answer), Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);;



Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
<LinearLayout android:id="@+id/linearLayout1" android:layout_height="match_parent" 
 android:orientation="vertical" android:layout_width="match_parent">
    <TextView android:id="@+id/textView5" android:text="My Dynamic Form Layout" 
  android:layout_height="wrap_content" android:layout_width="match_parent" 
  android:textStyle="bold" android:textSize="25sp" android:paddingBottom="10dp">
    <ScrollView android:layout_height="match_parent" android:id="@+id/scrollView1" 
        <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" 
   android:orientation="vertical" android:layout_height="match_parent">

Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.as400samplecode" android:versionCode="1"
    <uses-sdk android:minSdkVersion="13" />

    <application android:icon="@drawable/icon" android:label="@string/app_name"
        <activity android:name=".DynamicLayoutActivity"
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


Recommended Reading


  1. Thanks for this.. I have not tried it but seems to be exactly what I needed. I was able to dynamicaly add views but was at a loss of how to save the data. Thanks

  2. Hi, Thanks i have implemented this.

    I want to know that how i can save these dynamic created fields(TextView, EditText)etc In the db so that if i visit again it remains their.


  3. Perfect. Exactly what i was looking for.

  4. Aaah dude, you saved my arse, thanks for sharing the wealth of ya knowledge

  5. Thanks Man... :)

  6. Hi
    It is well-written helps a lot to beginners...

    thanks for sharing..

  7. Thanks Dude. this was really helpfull.

  8. Superb man.. Thanks.. Got a lot of hints to do my job...

    1. dude please tell me exactly what this program doing!??

  9. Hi,

    This is karthick my question is actually what's it does .I can't uderstand what happening in the output.simply it displays everything....please tell me!!!!

  10. Works very well! Thank you!!

  11. Nice post.Give it up. Thanks for share this article. For more visit:Web App Development

  12. Nice post.Give it up. Thanks for share this article. For more visit:Web App Development

  13. Thanks for the post...from all the blogs/articles/tutorials I've read so far, this post make sense..(noob student here)...

  14. Is it Possible to supply Xml File at RunTime And Disply Its UI .

  15. Awesome tutorial. Thanks a lot!!!

  16. hi sir, your tutorial is awesome but can you make it more simple?

  17. Awesome tutorial. Thanks a lot!!!

  18. Dear sir please : how to take value from the radiogroup ctreated at run time from java as you done it (rg) if we have loop through that .....

  19. Button and its click events in android

  20. This comment has been removed by the author.

  21. dịch vụ kế toán thuế tại ninh bình
    dịch vụ kế toán thuế tại vĩnh phúc
    dịch vụ kế toán thuế tại hưng yên
    dịch vụ kế toán thuế tại phú thọ
    dịch vụ dọn dẹp sổ sách kế toán
    dịch vụ dọn dẹp sổ sách kế toán tại thái bình
    dịch vụ dọn dẹp sổ sách kế toán tại phú thọ
    dịch vụ dọn dẹp sổ sách kế toán tại hưng yên
    dịch vụ dọn dẹp sổ sách kế toán tại quận hải dương
    dịch vụ dọn dẹp sổ sách kế toán tại hải phòng
    dịch vụ dọn dẹp sổ sách kế toán tại quận thanh trì
    dịch vụ dọn dẹp sổ sách kế toán tại quận hoàng mai
    dịch vụ dọn dẹp sổ sách kế toán tại quận hai bà trưng
    dịch vụ dọn dẹp sổ sách kế toán tại quận hoàn kiếm
    dịch vụ dọn dẹp sổ sách kế toán tại quận từ liêm
    dịch vụ dọn dẹp sổ sách kế toán tại quận ba đình
    dịch vụ dọn dẹp sổ sách kế toán tại quận tây hồ
    dịch vụ dọn dẹp sổ sách kế toán tại quận đống đa
    dịch vụ dọn dẹp sổ sách kế toán tại bắc ninh
    dịch vụ dọn dẹp sổ sách kế toán tại quận tphcm
    dịch vụ dọn dẹp sổ sách kế toán tại quận cầu giấy
    dịch vụ dọn dẹp sổ sách kế toán tại quận long biên
    dịch vụ dọn dẹp sổ sách kế toán tại quận hà đông
    dịch vụ dọn dẹp sổ sách kế toán tại quận thanh xuân
    dich vu hoan thue gtgt

  22. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.

  23. Superb post. We should make a blog for students to improve their writing ability. This rewriting services sites are available here for students.