Suppose I have a simple layout xml like the following:


    android:layout_height="wrap_content" />

Are there any differences in the following calls? and which one should i use?

button = (Button) getLayoutInflater().inflate(R.layout.button, null);


View v = getLayoutInflater().inflate(R.layout.button, null);
button = (Button) v.findViewById(;

No correct solution


This one creates a new view with the given layout where 'R.layout.button' is generated by the name of the xml file 'button.xml'. Each time you call .inflate(...) you will get a new instance.

View v = getLayoutInflater().inflate(R.layout.button, null);


While that one finds an existing view within a layout where is generated by the id name 'android:id="@+id/button01"'. Every time you call .findViewById( you will get the same instance since the view 'v' will be the same.

button = (Button) v.findViewById(;

The first option is cleaner and slightly more efficient.

Your layout inflater will return a Button. With the first option, you gain access to the Button directly. With the second option, you cast the button down to a View and then look for the view with a given ID, which is an extra useless comparison, since the view with the ID you're looking for in the hierarchy happens to be the button itself. So in the second option, v == button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow