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.

  24. Thanx sir..... Your articles are awesome


  25. Wonderful blog! I found it while searching on Yahoo News. Do you have any suggestions on how to get listed in Yahoo News? I’ve been trying for a while but I never seem to get there! Many thanks.
    2048 game | five nights at freddy's 4 | five nights at freddy's 3 | fireboy and watergirl | fireboy and watergirl 4||red ball | age of war

  26. I am certain this post has offered me some assistance with saving numerous hours of perusing other related presents just on find what I was searching for. Much obliged!
    Case Study Analysis

  27. I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that's at the other blogs.
    ColdFusion Homework Help

  28. This comment has been removed by the author.

  29. Website you manage very neat and not boring. I was really amazed by you. The contents of the article is very original. thanks for the work, may be a inpirasi for everything obat paru paru basah

  30. really well explanation about android textview,Button,radio button.. Android Training in chennai

  31. My friend recommended this blog and Power Plant Engineering Project Help
    he was totally right keep up the fantastic work!

  32. Electrical Assignment Online Help
    I’m really impressed with your article, such great & usefull knowledge you mentioned here

  33. it's really nice and meanful. it's really cool blog. Linking is very useful have really helped lots of people who visit blog and provide them usefull information.

  34.   I loved the way you discuss the topic great work thanks for the share.
    Assignment Homework Help

  35. I personally like your post, Online Term Paper writing Help
    you have shared good article. It will help me in great deal.

  36. Thanks for sharing information very interesting and useful. Do not forget to visit our website to share information and knowledge about health Obat Penghancur Batu Empedu

  37. may be useful for all, helpful article once and pardon me permission to share also here :

    Obat tulang keropos
    Obat susah kencing tradisional
    Obat penurun berat badan

  38. Here at this site really the fastidious material collection so that everybody can enjoy a lot. font converter online

  39. We are really happy to hear that android views can be used along with static XML layouts to design. Thanks for enlightening us in this matter. Look no further for affordable capstone paper writing services as you can get such writing help by clicking on this link: Capstone Paper Writing Help

  40. Bảng giá dự án chung cư the emerald mỹ đình giá từ 30tr/m2
    Giá bán căn hộ the k park Văn phú là bao nhiêu
    Đặt mua dự án dự án icid complex lê trọng tấn

  41. Thank you for sharing them! I hope you will continue to have similar posts to share with everyone!
    html color

  42. This is one of the best pages I've visited glad to be in your yard this amazing I find your site from gogole. Thanks for sharing, and I would be very happy and happy if you are also willing to visit to our website and read them to share information and knowledge about health, disease and treatment. Thank you and may be beneficial for all.
    Obat Gatal Di Vagina

  43. Thanks for sharing the information...Success for the website, as well as the previously asked permission to visit here ...
    Obat Bursitis | Obat Infeksi Tulang | Obat Gastroenteritis atau Radang Lambung | Produk Green World Original 100% Bergaransi | Obat Step

  44. Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.
    Click Here

  45. The TruthSpy monitoring app is one of the best on the market. Check it out for yourself

  46. Oh yes the problem i need to find. Your article provides useful information that i am looking for. I will often visit this site.

  47. nice this blog.
    You put really very helpful information. Keep it up. Keep blogging. I’m looking to reading your next post.