What is the difference between setContentView and

2019-01-13 21:29发布

I am creating a tabs list with several fragments. I have noticed that, in the main activity, I used setContentView to get the layout xml and use findViewById to get the corresponding UI element config.

setContentView(R.layout.fragment_tabs);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, android.R.id.tabcontent);

However, in the different fragment class, I have to use the inflater instead.

View v = inflater.inflate(R.layout.webview, container, false);
WebView myBrowser=(WebView)v.findViewById(R.id.mybrowser);

And both function are used to get the layout xml to create an object, why is there a difference? Is the first one use during onCreate, and the second one during onCreateView? In what situation I should choose either of them?

1条回答
Deceive 欺骗
2楼-- · 2019-01-13 22:10

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

查看更多
登录 后发表回答