setContentView和LayoutInflater有什么区别? [英] What is the difference between setContentView and LayoutInflater?
问题描述
我正在创建带有几个片段的标签列表.
我注意到,在主要活动中,我使用setContentView
获取布局xml,并使用findViewById
获取相应的UI元素配置.
setContentView(R.layout.fragment_tabs);
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabManager = new TabManager(this, mTabHost, android.R.id.tabcontent);
但是,在不同的片段类中,我不得不使用充气机.
View v = inflater.inflate(R.layout.webview, container, false);
WebView myBrowser=(WebView)v.findViewById(R.id.mybrowser);
这两个函数都用于获取布局xml来创建对象,为什么会有区别?是onCreate
期间的第一个用途,而onCreateView
期间的第二个用途?在什么情况下我应该选择其中一个?
setContentView
仅是Activity
方法.每个Activity
都提供一个ID为"@+id/content"
的FrameLayout
(即内容视图).您在setContentView
中指定的任何视图将是该Activity
的视图.请注意,您还可以将视图实例传递给此方法,例如setContentView(new WebView(this));
您所使用的方法的版本将在后台为您放大视图.
onCreateView
的生命周期方法,该方法返回一个视图(如果有一个视图).最常见的方法是用XML扩展视图并以此方法返回它.在这种情况下,您需要自己充气.片段没有setContentView
方法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?
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
这篇关于setContentView和LayoutInflater有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!