Activity has one ViewRoot and usually one Window attached to it. Activity is used for screen display the entire Window. Views are attached to this Window. Every Window has a Surface and Surface uses Canvas to draw on the surface. setContentView(View) is a method exclusively available for Activity. Internally it calls the setContentView(View) of Window. This method sets the activity content to an explicit view.


Fragments, on the other hand, have a lifecycle method called onCreateView which returns a view (if it has one). The most common way to do this is to inflate a view in XML and return it in this method. View inflate (int resource, ViewGroup root, boolean attachToRoot) used for inflating view hierarchy from the specified xml resource. LayoutInflater is used to instantiate layout XML file into its corresponding View objects. Basically the purpose is to create view objects at runtime depending on the requirement. Best example is the AdapterViews like ListView, Spinner etc, where a single view object corresponding to single record is created at run time depending on the number of records.

To attach view to parent view, set attachToRoot to true and specify the root view. For example to programmatically add below Button to a LinearLayout inside of a Fragment or Activity, use layout inflater.

<Button xmlns:android=""

// mLinearLayout is root view
inflater.inflate(R.layout.custom_button, mLinearLayout, true);