SetContentView() is a part of class. It helps to set our content or render our layout on the screen.

Based on the value given by the user, views will be inflated and rendered after the measurement of the screen, root view, and its child views. Well, here is everything you need to know about setContentView() method.

SetContentView() method is 3 types.

 1) setContentView(int resourceId)

2)setContentView(View view)

3)setContentView(View view, android.view.ViewGroup.layoutparams params)

These all methods available from API level 1. Let’s talk more about these types.


setContentView(int resourceId)

how setContentView() works in android
This method uses layout constant from automatically generated class. class holds many static constant values in nested classes. So that you can access directly by specifying R class and nested class.

Nested Layout class contains layout resource constants to ease the availability of actual files in the resource directory.

At runtime, System will select the appropriate layout based on orientation and other factors like language and region. But default it will select the layout in res/layout directory.

Here, R.layout.activity_main is an integer value contained inside of layout class in file. Using this integer value Android system will look in res/layout directory. That’s how android finds the correct layout.

If you are using XML layout do not try to initialize views before calling setContentView(R.layout.layout_name), because without inflating the layouts, there are no actual views in memory. It will lead to NullpointerException.

setContentView(android.view.View view)

Set any view as your activity’s content. View’s height and width set to MATCH_PARENT as default.

You probably need to add an import android.widget.TextView; statement.

setContentView(View view, ViewGroup.Layoutparams)

Extension of setContentView(View view) method. Here you can specify view’s parameters.

You can add child views to Linearlayout using addView() method.

  • You can call many times setContentView() method, but it works only at the last call.
  • You can use setContentView() outside of the onCreate() method.
  • ListActivity does not use setContentView() Because it already contains a listview and use setListAdapter() to populate.
  • In fragments, LayoutInflater does layout rendering work with inflate() method. Just equivalent to setContentView().
  • Sometimes, you need to display a layout from many layouts based on any condition. Like showing login or signup page. So there is no need to create two activities. Just use if statement or other depends on your needs and do just like below.


That’s all for now. Is there any suggestions, please comment below.