的setContentView和充气的区别区别、setContentView

2023-09-04 03:54:22 作者:时光缱绻如画

我创建一个标签列表,几个片段。 正如我已经注意到,在主要活动中,我用的setContentView得到的布局xml和使用viewbyID得到相应的UI元素的配置。

I am creating a tabs list with several fragment. As I have noticed that, in the main activity, I used setcontentview to get the layout xml and use viewbyID 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 used the inflater instead.

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

和这两个函数用于获取布局XML来创建对象,为什么会有差别?是第一个使用的时候OnCreate中,并在oncreateview第二个用?在什么情况下我应该选择其中一方?谢谢。

And both function are used to get the layout xml to create an object, why there is difference? Is the first one use when oncreate, and the second one use on oncreateview? In what situation I should choose either of them ? Thanks.

推荐答案

的setContentView只是一个活动的方法。每个活动都具有的FrameLayout ID为@ + ID /内容(即内容视图)。无论大家认为你的setContentView指定将认为该活动。请注意,您也可以通过视图的一个实例,以这种方法,例如,的setContentView(新的WebView(本));您使用的是会膨胀幕后的观点对你的方法的版本。

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.

片段,在另一方面,有一个称为onCreateView生命周期方法,它返回一个视图(如果有的话)。要做到这一点,最常用的方式是可以填充视图的XML及在该方法中返回。在这种情况下,你需要自己,虽然它充气。片段没有的setContentView法

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