Blog Archive

Android LayoutInflater - Dynamically Add and Remove Views using Java code

How to manipulate Android screen using predefined XML layouts? This can be done with the help of LayoutInflater. This class is used to instantiate layout XML file into its corresponding View objects. It is never to be used directly -- use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:

LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);

Click here if you are interested in generating layout views such as Button, TextView, EditText, RadioButton, CheckBox, ToggleButton, etc. programmatically in Java code.

Source for main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
            <LinearLayout android:id="@+id/linearLayout1"
                android:layout_height="wrap_content" android:orientation="horizontal"
                <Button android:text="Add View" android:layout_height="wrap_content"
                    android:id="@+id/add" android:layout_width="0dp"
                    android:layout_weight=".5" />
                <Button android:text="Remove View" android:layout_height="wrap_content"
                    android:id="@+id/remove" android:layout_width="0dp"
                    android:layout_weight=".5" />
            <LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" 
    android:layout_width="match_parent" android:orientation="vertical">

Source for hidden.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent" android:id="@+id/hiddenLayout">
    <TextView android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="This is a Text View" android:layout_height="wrap_content"
        android:id="@+id/textView1" android:layout_width="wrap_content" />
    <CheckBox android:text="CheckBox1" android:id="@+id/checkBox1"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <CheckBox android:text="CheckBox2" android:id="@+id/checkBox2"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <CheckBox android:text="CheckBox3" android:id="@+id/checkBox3"
        android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioGroup android:id="@+id/radioGroup1"
        android:layout_height="wrap_content" android:layout_width="wrap_content"
        <RadioButton android:text="Radio Button1"
            android:layout_width="wrap_content" android:id="@+id/radio0"
            android:layout_height="wrap_content" android:checked="true" />
        <RadioButton android:text="Radio Button2"
            android:layout_width="wrap_content" android:id="@+id/radio1"
            android:layout_height="wrap_content" />
        <RadioButton android:text="Radio Button3"
            android:layout_width="wrap_content" android:id="@+id/radio2"
            android:layout_height="wrap_content" />


Source for

package com.as400samplecode;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DynamicViews extends Activity implements OnClickListener{

    public void onCreate(Bundle savedInstanceState) {
        View buttonAdd = findViewById(;

        View buttonRemove = findViewById(;
    public void onClick(View v) {
        switch (v.getId()) {
            //Check if the Layout already exists
            LinearLayout hiddenLayout = (LinearLayout)findViewById(;
            if(hiddenLayout == null){
                //Inflate the Hidden Layout Information View 
                LinearLayout myLayout = (LinearLayout)findViewById(;
                View hiddenInfo = getLayoutInflater().inflate(R.layout.hidden, myLayout, false);

            //Get References to the TextView 
            TextView myTextView = (TextView) findViewById(;
            // Update the TextView Text
            myTextView.setText("This is not the original Text defined in the XML layout !");
            View myView = findViewById(;
            ViewGroup parent = (ViewGroup) myView.getParent();

            // More buttons go here (if any) ...


Source for AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    <uses-sdk android:minSdkVersion="13" />

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


Android dynamic layout using XML

Android dynamic layout using XML


  1. This example is crystal clear - thanks very much! Very useful.

    1. Wow. good post. I’d like to write like this too , taking time and real hard work to make a great article…
      Call Girls Service Ajmer

  2. very tough to understand.
    but thanks for guideline

  3. thanks a lot. well done

  4. Thanks for this! I've been trying to understand WHY one uses LayoutInflater and this makes it very clear.

  5. Hi Nice example... thanks a lot

    But while remove we need to check this condition in java code. Otherwise it will throw NullPointerException.

    View myView = findViewById(;
    if(myView != null)
    System.out.println("---------view is not null");
    ViewGroup parent = (ViewGroup) myView.getParent();

    1. yes we need to check for the null condition else throws exeption....nice example

  6. Thanks for tutorial.. :D
    This is what i want..

  7. Nice post.Give it up. Thanks for share this article. For more visit:android development

  8. Nice post.Give it up. Thanks for share this article. For more visit:android development

  9. Though the name suggest that you E Ledden can only take notes but that is not limited to only text;

  10. Thank you very much. am converting my project from swing to android. am learning android and I needed a code like this. Am adopting it


  11. Hi, if I add multiple items how can I remove a certain one? Thanks


  12. Hey i tried this code its nice but m getting nullPointerException Error when m trying to add dynamic checkboxes in one of my Views, this is code
    public void onClick(View v) {
    switch(v.getId()) {
    LinearLayout checkboxLayout1 = (LinearLayout) findViewById(;
    Dbadapter details = new Dbadapter(this);;
    data =details.getDetailedSymps(sympId);
    for (int i = 0; i < data.length; i++) {
    CheckBox cb = new CheckBox(this);
    Can you plz tell whats wrong with this?


  13. ArrayList appList = new Gson().fromJson(response, (java.lang.reflect.Type) type);

    for(int i = 0; i < appList.size(); i++) {
    TextView view=new TextView(getBaseContext());
    Integer color = Integer.parseInt("424242", 16)+0xFF000000;
    Integer checkcolor = Integer.parseInt("424242",16)+0xFF000000;
    CheckBox cb = new CheckBox(getBaseContext());

    // cb.setDrawingCacheBackgroundColor(checkcolor);

    int flag=appList.get(i).getFlag();


  14. Thanks! This was very helpfull. I used the inflater part only to place some graphica on top of a camera preview. It works like a charm! ;)

  15. There should be more info in comments for beginners like me.

  16. how i can add a spinner dynamically

  17. thanks... this was very helpful

  18. good tutorial........thankssssss

  19. If i want to remove add more than one and i want to click remove view and i am only remove one item then how it is possible.

  20. Perfect article to read and also want to share this awesome post.
    Call Girls in Dehradun
    Gurgaon Escorts

  21. The war between humans, orcs and elves continues earn to die . Lead your race through a series of epic battles, using your crossbow to fend off foes and sending out units to destroy castleshappy wheels . Researching and upgrading wisely will be crucial to your success! There are 5 ages total and each one will bring you new units to train to fight in the war for you cause.
    earn to die 2
    Whatever you do, don’t neglect your home base because you cannot repair it and once it is destroyed, you lose! Age of War is the first game of the series and really sets the tone for the Age of War games . Also try out the Age of Defense series as it is pretty similar.
    In this game, you start at the cavern men’s age, then evolvetank trouble ! There is a total of 5 ages, each with its units and turrets. Take control of 16 different units and 15 different turrets to defend your base and destroy your enemy.
    The goal of the game also differs depending on the level. In most levels the goal is to reach a finish line or to collect tokens. Many levels feature alternate or nonexistent goals for the player. The game controls are shown just under gold miner. Movement mechanisms primarily include acceleration and tilting controls. cubefield
    It consists of a total of 17 levels and the challenge you face in each level increases as you go up. unfair mario The game basically has a red ball that has to be moved across the various obstacles in its path to the goal. slitherio


  22. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this fiel
    Red Ball | | duck life | Slitherio
    Red Ball 2 | Red Ball 3 | Red Ball 4

  23. This is very useful for me thank you for share this information. it will more help to me i really happy to see this blog.
    custom essay writing service

  24. I am very appreciate by this.I am Sakshi Ahuja, a passionate Delhi model girl living in the middle of Delhi city.

  25. Good information .I am shruti arora, a passionate Delhi model girl living in the middle of Delhi city.

  26. Hi guy's my name is Akshita Chopra. I am very beautiful and cute girl in Delhi. I am a independent model.

  27. I like this post. I have got such a good information from here. I am going to bookmark this blog this is very informative. Thanks

  28. I am going to bookmark this post i like this post very much thanks for such a good post. Thanks a lot.

  29. Hi my name is Rekha Shukla. I am a independent beautiful girl in Delhi. I can make you feel good with my service. I am working in a multinational company as a computer operator.
    Escorts Service In Delhi

  30. Hello everyone, My name is Priyanka Singhania and this is my Independent Delhi services. I am here to offer you top class independent services in Delhi, that can blow up your mind.
    Female Escort In Delhi

  31. Sampark Foundation There is a service named Nasha Mukti Kendra in delhi that is selling successfully to previously up pay for enjoyable minister to to the victims of alcohol addiction. You may log in to www. for more details.

    More information just click

    Web- Nasha Mukti Kendra in Delhi

  32. Call us +91 9619919443 for great female escorts services in Goa. Our site link is: Goa escorts world. Services available 24/7.


  33. UAE autonomous escorts are amazingly receptive, expressive in feelings and imaginative at great time. Its simple to request vip Dubai escorts by a phone,which said in the site.

    Call Girls in Dubai |
    Pakistani Call Girls in Dubai |

    Indian Call Girls in Dubai |

    Pakistani Escorts in Dubai |

  34. Surrogate Mother in Delhi You may pick go charitable way and just demand them to succession care of medical charges alone. if you would pick to go via Surrogate Mother in Delhi there are generally definite total for payment. An advantage of going via agency is, they usually pay out surrogate mothers much higher than couples would via a private surrogacy.
    Surrogate Mother in Delhi | Surrogacy Agencies in New Delhi

  35. Your website is very nice and interesting, the website may increasingly exist and no one obat tbc tradisional pengobatan tradisional epilepsi

  36. Your website is very interesting, it is not boring and full of inspiration that you devote. Your website deserve to be the best Obat Usus Buntu Herbal


  37. Sakina Siddiqui Udaipur Escorts Girls in Your City @ Independent Udaipur Escorts
    Aashi Gupta Udaipur Escorts Girls in Your City @ Independent Udaipur Escorts
    Vanya Deshmukh Udaipur Escorts Girls in Your City @ Independent Udaipur Escorts
    Mukti Rana Udaipur Escorts Girls in Your City @ Independent Udaipur Escorts
    Salma Kazi Udaipur Escorts Girls in Your City @ Independent Udaipur Escorts
    Talita Verma Bangalore Escorts Girls in Your City @ Independent Bangalore Escorts
    Neha Saxena Bangalore Escorts Girls in Your City @ Independent Bangalore Escorts

  38. I was very impressed with you. website you create highly qualified and highly original contents obat paru paru basah obat tradisional tbc obat radang usus

  39. Thanks for Nice and Informative Post. This article is really contains lot more information about This Topic obat sinusitis

  40. Your website is very interesting, it is not boring and full of inspiration that you devote. Your website deserve to be the best obat ambeien, obat usus buntu, obat limpa bengkak

  41. If you need a good tutorial for getting started with NativeScript check out Getting started with NativeScript

  42. Thank you so much admin is already providing the information to us and here we are sorry permission to share medical articles may be useful for all of you in particular who are looking for :

    Obat radang sendi
    Obat tumor rahang
    Obat mata minus

  43. After you click the image, you'll be directed to the VIP Escorts in Chandigarh complete profile wherever you'll have all the knowledge concerning her in bigger details.

  44. Welcome to My web site : ,Our Escorts in Ahmedabad have all that you wish to have – a curvy physique, killer looks and not so normal intellect which permit you to do whatever you need to do with them. Their body is a playground for you. In each a part of it, they have sweet surprises for you.

  45. The Event Organisers of india
    We event organsiers fulfill customer satisfaction by understanding and monitoring event objective, Event scope, event plan, Event Contact List, Event Details, Event Task List, events approval, Event Bookings and Permits, Event Notification, Event Monitoring, and take feedback as Event Review. We, the Event organisers and our committee work closely with a financial manager to ensure the event follows the relevant financial budget. There will always be minor difficulties and challenges; however, hopefully most of these will have been considered and there will be contingency plans to address problems by our team mates and event organsiers. We, Event organiser, a developer in shaping good and mesmerizing events. You can find us on or email us at

  46. Chandigarh is lively plus one will find large amount of escorts around. All of the escorts are well- well and qualified -briefed to make sure that they merely provide total satisfaction and greatest services. All of the escorts in Chandigarh are amusing, large and therefore are qualified enough to provide friendship greatest.
    Chandigarh escorts
    Chandigarh escorts service
    Chandigarh escort
    Chandigarh escort service
    Chandigarh Independent escorts
    Chandigarh female escorts
    Chandigarh call girls
    escorts in Chandigarh
    escorts service in Chandigarh
    escort in Chandigarh
    Chandigarh call girl
    Independent escorts in Chandigarh
    Female escorts in Chandigarh

  47. Call girl that is Chandigarh escorts establish themselves as a correct company in their opinion. Their approaches that are favorable are s O enchanting that customers that are worldwide stay silly to acquire their services. Being incredibly eloquent in Language, they cause them to become as happy as clam by making use of their services and have an extremely simple discussion using the non citizens. Because of this, these escorts are becoming well-known all around the globe.


  48. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write.
    Thanks for sharing !
    tanki online 2 | 2048 game online

  49. I am enjoying moviestarplanets hack games and this is very easy and simple to play. I have got a diamonds and star coins because of this a special membership. Now I became a celebrity and I have lots of fans upto 12 months. Msp is also available on androids mobile phones.

  50. Thank you so much admin is already providing the information to us and here we are sorry permission to share articles may be useful and help you in particular are looking for cara mengatasi

    bab berdarah


  51. Thank you so much admin is already providing the information to us and here we are sorry permission to share articles may be useful and help you in particular are looking for :

    obat nyeri sendi tulang
    Obat osteoarthritis
    Obat gastroenteritis

  52. The Companions in Chandigarh are better to spend time in Asia in Chandigarh or every other town. We offer journey Companions for several days 2 days, 1 week or journey. Regarding reserving a visit Companion, also have to help make the cost first.We possess female escorts from throughout Asia and you've to consider booking. They originate to Chandigarh regarding research from numerous towns of Indian, regarding questioning around and in research of function. Most our Chandigarh Companion Call-Girls to become selected in the girls that are greatest depends upon physic their character and existence of thoughts. We offer numerous types of Companions to the customers like.

  53. Looking for Russian Call Girls in Mahipalpur, contact us for the best Russian escort services in mahipalpur, Aerocity, Vasant Kunj in 5 star hotel facilitie Russian Call Girls in Mahipalpur

  54. I am really enjoying reading your well written articles. I think you spend numerous effort and time updating your blog.Please keep up the good articles!
    Gurgaon Escorts, Escorts in Gurgaon
    Escorts in Gurgaon, Female Escorts in Gurgaon
    Independent Escorts in Gurgaon, Gurgaon Escorts

  55. Gurgaon Partners is a High-class Partners relationship providing a the best quality companions advantages in the Gurgaon. I was looking for something like this… I thought that it was quiet surprising, in a faultless world you will keep growing such objectives… .Keep analyzing. Delhi and Gurgaon.
    Roshnikhanna Escorts Service | Mehar Kaor | Roshnikhanna Escorts | Sofiya loani | Delhi Escorts | Gurgaon Escorts Agency, Escorts in Gurgaon | Gurgaon Escorts Service

  56. Limitless options can be offered by the escort as well as in reality the big catalog of services that are unique addresses the requirements and various dreams. If you should be an individual searching for the organization of an Chandigarh escort, you are able to check websites out. Companion agencies provide the customers incredible selection of services. If you should be browsing chandigarh escorts, you are able to desire for an escort provides maximum fulfillment and enjoyment and to amuse you. Browsing a city-like Chandigarh will end up more enjoyable using the stunning and wise friend.

  57. Consequently its escort and one of the best chandigarh escorts contemplate her with this specific trip that is fascinating together with you. Precisely why could it be recommended to become about the holiday a today having you need to be asking that. Theyare not guests because they're consequently enjoyable that within handful of moments of dialogue you will feel just like you recognize them properly to start with. Why these escorts in Chandigarh under we have collected will be the best holiday companion many facets that may clarify.

  58. Like a Zirakpur Escort Support that is really our title is not truly unimportant consequently we often proceed the kilometer that is additional to verify assistance that is complete from our client that is complete. We often review and usually capitalist assistance suggestions of versions to become moving by e-mail as well as consider actions that are required to disrupt any selflessness.

  59. Escort in Chandigarh If you really serious about spending unforgettable time with me then you must have all the following details with you before you email or call.

  60. By the way, Thank you for sharing with us, and we sincerely hope you will continue to update or post other articles.
    pengobatan kanker rongga mulut

  61. This article is very much helpful and i hope this will be an useful information for the needed one. Keep on updating these kinds of informative things...
    iOS Training in Chennai
    Android Training in Chennai
    php Training in Chennai


  62. “Among many CBSE Open Schools Patrachar School counts as best Cbse Correspondence or CBSE Private Form in Delhi for admission in 12th Class. Cbse Correspondence forms Contact No.”

    CBSE Patrachar School

  63. We feel fantastic in yourself in addition to we feel did most knowledgeable and performing courses to provide the most excellent at-one a chance to anyone in most available and thrilling method of create excellent occasions, Being design we feel especially available to visit and choose out-station and much more.

    panchkula female escort
    panchkula female escorts

    escorts in mohali
    escorts service in mohali

    escort service in Zirakpur
    Vip escort service in zirakpur

  64. You’ve written nice aborsi post , I am gonna bookmark this obat aborsi page , thanks for info. I actually appreciate your own jual obat aborsi position and I will be sure to come back here.his is a really good post. Must admit that you are among the best bloggers I have read. Thanks for posting this informative article of obat aborsi murah . You may havce a lot of jual obat aborsi, as well jual obat aborsi surabaya.
    Good post website. I learn something new jasa website and challenging on jasa buat website blogs I stumbleupon every day of jasa pembuatan website.It will always be exciting to read content from other writers and use a jasa pembuatan web and harga jasa pembuatan website little something from their jasa pembuatan website

    Thank you for providing information from your jasa pembuatan website profesional website. On of the good jasa website perusahaan website in search results .
    I would once again praise kandungan to god about this amazing post menggugurkan. Thank you so much for the detailed information penggugur kandungan. I love to read tips from cara menggugurkan kandungan who are really successful with what they do. It inspires me of obat an I learn a lot penggugur witch helps me to grow my business obat penggugur kandungan faster.
    Well, Thanks a lot of aborsi for such a wonderful post of obat aborsi, the stuff posted were really obat interesting and useful jual obat aborsi. The quality of aborsi the content was good and clear.
    I would once again praise to god about this amazing post mesin coding. Thank you so much for the detailed information. I love to read tips from people who are really successful with what they do inkjet printer industri. It inspires me an I learn a lot witch helps me to grow my business faster.
    I want to thank you for interesting and helpful information and I like your point of view. Thank you!- I love to read this type of material Good and attractive information I take from it..Thank you for posting such a good article .

  65. Get enjoyable deals upon Hotel near New Delhi railway station, India. Book online, pay at the hotel. Read hotel reviews and choose the best hotel arbitration for your stay.
    Budget Hotel Central Delhi
    Best Budget Hotel In Delhi Paharganj