What does it mean to inflate a view from an xml file?

Brendan Weinstein picture Brendan Weinstein · Jan 2, 2011 · Viewed 129.3k times · Source

I am new to android development and keep coming across references to Inflating views from a layout xml file. I googled and searched the development guide but still wasn't able to pick up a sense for what it means. If someone could provide a very simple example, it'd be much appreciated.

Answer

Cristian picture Cristian · Jan 2, 2011

When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:

class Name extends Activity{
    public void onCreate(){
         // the OS will inflate the your_layout.xml
         // file and use it for this activity
         setContentView(R.layout.your_layout);
    }
}

You can also inflate views explicitly by using the LayoutInflater. In that case you have to:

  1. Get an instance of the LayoutInflater
  2. Specify the XML to inflate
  3. Use the returned View
  4. Set the content view with returned view (above)

For instance:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4