Layout resources in Android

One thing that often confuses developers new to the Android platform is the handling of layout resources. The xml files describing the layouts are magically transfered into a more efficient binary format behind the scenes and hidden away – leaving the developer with a static reference to the resources via the R.java file.

By using the setContentView(int layoutResId) method of the Activity class your layout will be displayed on the screen. Behind the scenes the Android platform is creating all the view objects contained in your layout xml file provided to the setContentView(int layoutResId) method. This process of creating view objects out of layout resources is referred to as layout inflation.

So far so good. This means that before the setContentView(int layoutResId) method is called the findViewById(int resId) method will return null for any view references in the layout, causing some potential NullpointerExceptions.

To avoid these errors it’s a good habit to place the setContentView(int layoutResId) method call at the very top of the onCreate() method.

In some cases you will have to do the layout inflation by yourself, i.e. when you want to set a custom view to a Dialog or a Toast. To inflate a view you use the LayoutInflater class. There’s a number of different ways to get a handle to a LayoutInflater:

To actually create the view object you use the inflate() method of the LayoutInflater. In the most straightforward form this method has the signature:

Note that the resource is referring to a layout xml file resource, NOT the id of the view object that you want to inflate. First inflate the layout resource and then get a handle to the view object by using the findViewById(int resId) method.

The second attribute allows you to specify a ViewGroup object to be the root view of the inflated object(s) specified by your layout xml file. This means that the inflated view object(s) are attached as child views on the specified root ViewGroup object. Setting this value to null will simply return the inflated view object(s) without attaching them to a root view.

In this example the inflate method returns the mRoot object with the view objects contained in the layout_details.xml file attached as child views. So itemView and myRoot is actually referring to the same physical object.

17 Comments

  1. Wow. It looks nice… and works fine.
    Thank you.

  2. hung nguyen

    Jag vill vet hur man gör följande saker i android.

    1. Jag vill skapa en panel kalla den “person” med med tre widgets.
    1. En textview för som visar ett index
    2. Ett Edittext för att skriva in ett namn.
    3. en Edittext för att visa personens ålder.

    Jag ska ha multipla paneler av ovanstående panel. Det ska kunna läggas till en sådan varje gång man lägger till en person.

    Jag vill lägga dessa paneler i en LinearLayout eller ListView.

    Nu vill jag lägga till en adapter till ListViewn där varje element är en panel av “person”. Eftersom jag endast kommer ändra åldern hur desgna man en sådan layout ?

    //Hung

  3. rahul

    thanks for the post….it was really useful..!
    ///my code

    LayoutInflater inflater = LayoutInflater.from(this);
    AbsoluteLayout al=new AbsoluteLayout(this);
    View wind=inflater.inflate(R.layout.dialogbox,al);
    ad.setView(wind);
    EditText rate=(EditText)findViewById(R.id.rate);
    ad.setCancelable(true); // This blocks the ‘BACK’ button
    ad.setButton(, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    }
    });
    ad.show();

  4. Quasar

    thanks very much for this page!!!
    I was going crazy!!! clear examples or tutorial about LayoutInflater are so rare…
    thanks again man!

  5. Martin

    Man, I’ve spent days trying to figure out the basics of LayoutInflater … no books or official tutorials / dev guides have beeen of much help.

    Thanks a lot! :)

  6. Paramananda pradhan

    hi,
    This Example was help me to implement LayoutInflater.
    Very good useful Tips u have.
    thanks again ….tateresslife

  7. Saranya

    great post…thank you… :)

  8. Saranya

    good post…really helped..thank you… :)

  9. Bond

    Excellent!!! :):)

  10. Jess

    Thanks for this! I’ve been trying to understand what LayoutInflater is for and hadn’t been able to figure out from the API docs.

  11. julious

    I m still getting a null pointer exceptoin ..can u help me ?

    LayoutInflater inflater=LayoutInflater.from(this);
    LinearLayout myRoot = new LinearLayout(this );

    accountslistlayout=inflater.inflate(R.layout.accountnameslist, myRoot);
    ListView listView = (ListView)findViewById(R.id.accountnameslist);

    • Mattias Rosberg

      Given the code you have submitted it’s not possible to be 100% sure about what causes the NullpointerException in your code. My guess is that the listView variable is still null after your code has executed. Note that the findViewById() is by default only searching for the View with id R.id.accountnamelist in the layout specified by the setContentView() method in your Activity. I guess that your ListView is located in the accountslistlayout that you created using the LayoutInflator. In that case the code should look like this:

      ListView listView = (ListView)accountslistlayout.findViewById(R.id.accountnameslist);

      That is, you search for a view with id accountnameslist in the accountslistlayout layout.

  12. Dennis

    Good post. Thank you :)

  13. Venks

    Very detailed explanation and helpful.
    Thank you so much.

  14. Augustus

    Detailed Explanation..:)..Cheers..:)

  15. kumar

    Thanks for your clean tutorial about layout inflation..

Trackbacks for this post

  1. CountDownTimer within Dialog in Android

Leave a Reply