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="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="wrap_content" android:orientation="horizontal"
                android:layout_width="match_parent">
                <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>
            <LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" 
    android:layout_width="match_parent" android:orientation="vertical">
   </LinearLayout>
</LinearLayout>

Source for hidden.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/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"
        android:orientation="horizontal">
        <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" />
    </RadioGroup>

</LinearLayout>

Source for DynamicViews.java

package com.as400samplecode;

import android.app.Activity;
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{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        View buttonAdd = findViewById(R.id.add);
        buttonAdd.setOnClickListener(this);

        View buttonRemove = findViewById(R.id.remove);
        buttonRemove.setOnClickListener(this);
    }
   
    public void onClick(View v) {
        switch (v.getId()) {
       
        case R.id.add:
            //Check if the Layout already exists
            LinearLayout hiddenLayout = (LinearLayout)findViewById(R.id.hiddenLayout);
            if(hiddenLayout == null){
                //Inflate the Hidden Layout Information View 
                LinearLayout myLayout = (LinearLayout)findViewById(R.id.linearLayout2);
                View hiddenInfo = getLayoutInflater().inflate(R.layout.hidden, myLayout, false);
                myLayout.addView(hiddenInfo);
            }

            //Get References to the TextView 
            TextView myTextView = (TextView) findViewById(R.id.textView1);
            // Update the TextView Text
            myTextView.setText("This is not the original Text defined in the XML layout !");
            break;
       
        case R.id.remove:
            View myView = findViewById(R.id.hiddenLayout);
            ViewGroup parent = (ViewGroup) myView.getParent();
            parent.removeView(myView);

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

        }
    }
   
}

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=".DynamicViews"
                  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>

Android dynamic layout using XML

Android dynamic layout using XML

59 comments :

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

    ReplyDelete
  2. very tough to understand.
    but thanks for guideline

    ReplyDelete
  3. thanks a lot. well done

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

    ReplyDelete
  5. Hi Nice example... thanks a lot

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

    case R.id.remove:
    View myView = findViewById(R.id.hiddenLayout);
    if(myView != null)
    {
    System.out.println("---------view is not null");
    ViewGroup parent = (ViewGroup) myView.getParent();
    parent.removeView(myView);
    }

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

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

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

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

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

    ReplyDelete
  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

    Ruth

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

    TibiG

    ReplyDelete
  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()) {
    case R.id.sens:
    LinearLayout checkboxLayout1 = (LinearLayout) findViewById(R.id.Checkbox_Layout1);
    Dbadapter details = new Dbadapter(this);
    details.open();
    data =details.getDetailedSymps(sympId);
    details.close();
    for (int i = 0; i < data.length; i++) {
    CheckBox cb = new CheckBox(this);
    cb.setTextColor(Color.BLACK);
    cb.setButtonDrawable(id);
    cb.setText(data[i]);
    checkboxLayout1.addView(cb);
    }
    Can you plz tell whats wrong with this?

    ReplyDelete








  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;
    //view.setTextColor(Color.parseColor("#000000"));
    CheckBox cb = new CheckBox(getBaseContext());
    //cb.setBackgroundColor(checkcolor);

    // cb.setDrawingCacheBackgroundColor(checkcolor);

    cb.setText(appList.get(i).getName());
    int flag=appList.get(i).getFlag();
    if(flag==1)
    {
    cb.setChecked(true);
    }
    appList.get(i).setHtmlid(i+100);
    cb.setId(i+100);
    ll.addView(cb);
    cb.setTextColor(color);

    }
    listLength=appList;

    ReplyDelete
  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! ;)

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

    ReplyDelete
  16. how i can add a spinner dynamically

    ReplyDelete
  17. thanks... this was very helpful

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

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

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

    ReplyDelete
  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

    ReplyDelete

  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

    ReplyDelete
  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

    ReplyDelete
  24. I am very appreciate by this.I am Sakshi Ahuja, a passionate Delhi model girl living in the middle of Delhi city.
    http://sakshiahuja.com/

    ReplyDelete
  25. Good information .I am shruti arora, a passionate Delhi model girl living in the middle of Delhi city.
    http://shrutiarora.com/

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

    http://akshitachopra.com/

    ReplyDelete
  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
    http://aaditisharma.com/

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


    http://ayushikapoor.com/

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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. samparkrehab.com for more details.

    More information just click

    Web- Nasha Mukti Kendra in Delhi

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

    ReplyDelete

  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 |

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete

  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

    ReplyDelete
  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

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

    ReplyDelete
  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

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

    ReplyDelete