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.app.Activity;
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;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout2);

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

        // add edit text
        EditText et = new EditText(this);
        et.setText("Dynamic EditText!");
        et.setMinLines(1);
        et.setMaxLines(3);
        ll.addView(et);

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

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

        //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);
            rb[i].setId(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.setChecked(true);
        tb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        ll.addView(tb);

    }
   
    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);
            toast.show();
            saveAnswers();
            break;
            // More buttons go here (if any) ...

        }
    }
   
    public void saveAnswers() {
        LinearLayout root = (LinearLayout) findViewById(R.id.linearLayout1); //or whatever your root control is
        loopQuestions(root);
    }

    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;
                loopQuestions(group);
            }
        }
    }

    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);
        toast.show();

       
    }

}

Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<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">
 </TextView>
    <ScrollView android:layout_height="match_parent" android:id="@+id/scrollView1" 
  android:layout_width="match_parent">
        <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" 
   android:orientation="vertical" android:layout_height="match_parent">
       </LinearLayout>
    </ScrollView>
</LinearLayout>
</LinearLayout>

Source for AndroidManifest.xml

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

    <application android:icon="@drawable/icon" android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">
        <activity android:name=".DynamicLayoutActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Recommended Reading


72 comments :

  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

    ReplyDelete
  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.

    Thanks

    ReplyDelete
  3. Perfect. Exactly what i was looking for.

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

    ReplyDelete
  5. Thanks Man... :)

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

    thanks for sharing..

    ReplyDelete
  7. Thanks Dude. this was really helpfull.

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

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

      Delete
  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!!!!

    ReplyDelete
  10. Works very well! Thank you!!

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

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

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

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

    ReplyDelete
  15. Awesome tutorial. Thanks a lot!!!

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

    ReplyDelete
  17. Awesome tutorial. Thanks a lot!!!

    http://www.androidspot1995.com

    ReplyDelete
  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 .....

    ReplyDelete
  19. Button and its click events in android
    http://themasterworld.com/android-button-help-to-create-button/

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  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

    ReplyDelete
  22. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post. Keep up your work.  write-an-essay.org/college-paper

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

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

    ReplyDelete

  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  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

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

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

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

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

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

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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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.

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

    โกเด้นสล็อต

    ReplyDelete