From what I understand, the LayoutInflater converts XML into Views. But when I use Buttons, TextViews or other widgets in code, I simply have to use findViewById() without having to inflate these Views first. Are these views automatically inflated? If so, when are views automatically inflated and when do you have to inflate them manually?
-
Your basic question is "When do I need to manually inflate a view, and when is it done for me automatically?" Ankesh kumar Jaisansaria gave a good reply. Also look here: [Difference between setcontentview and inflater](http://stackoverflow.com/questions/17808177/difference-between-setcontentview-and-inflater). Finally, read this thread: [fragments vs activities and views](http://stackoverflow.com/questions/10478233/android-i-need-some-clarifications-of-fragments-vs-activities-and-views) – paulsm4 Apr 13 '16 at 04:02
-
Inflate just means translate from XML to actual View objects. findViewById just locates the actual view object so you can manipulate it. – Doug Stevenson Apr 13 '16 at 04:08
4 Answers
You just have to inflate an xml layout, and then all the viewgroups and views (buttons,textview,edittext,etc.) will automatically be shown.
So in an Activity class, oncreate method has a line SetContentview(), this inflates the xml layout.

- 1,563
- 4
- 26
- 44
An Activity
needs to include a call to setContentView(R.layout.<your_layout_here>)
in its onCreate
method. That inflates the XML in the specified layout into the view hierarchy for the Activity
. For a Fragment
, override the onCreateView
method like below:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.<your_layout_here>, container, false);
}
Once you've inflated a layout (and all of its children View
s) into the view hierarchy, you can then use findViewById(R.id.<your_view_id>)
to get a reference to the actual View
object that you've inflated into the hierarchy and play with it.

- 761
- 7
- 18
you inflate your views manually if you create your activity and xml manually.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
}

- 357
- 4
- 14
Few things are here:
1. View for your activity(UI screen), that is set by setContentView() method.
2. View for a specific UI component e.g. Button, that is either created in xml of your activity_layout or you can inflate a separate xml layout file for your specific UI component. The best example and use is like inflating an xml layout file for your customised Toast.
So, here is the thing that relates setContentView() and inflating an xml layout file for a separate view: Both of these provides a layout for view and view components, both of them creates a binary output for layout and use them as described above.

- 89
- 3