What is the difference between setContentView and LayoutInflater? What is the difference between setContentView and LayoutInflater? android android

What is the difference between setContentView and LayoutInflater?


setContentView is an Activity method only. Each Activity is provided with a FrameLayout with id "@+id/content" (i.e. the content view). Whatever view you specify in setContentView will be the view for that Activity. Note that you can also pass an instance of a view to this method, e.g. setContentView(new WebView(this)); The version of the method that you are using will inflate the view for you behind the scenes.

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. In this case you need to inflate it yourself though. Fragments don't have a setContentView method

Activities and views both have a method called findViewById(). The activity version will search for a view with the given id inside of it's content view (therefore, internally, it will call contentView.findViewById()). This means that the contentView needs to be set before it becomes usable. Like setContentView, fragments don't have a method for findViewById (which makes sense, because there is no content view). Simply use getView().findViewById() instead for the same behaviour.

LayoutInflater.inflate just inflates and returns a view (you can use this anywhere). You still need to set that view as the content view within an Activity