您的位置:首页 > 其它

setContentView()和inflate()的区别

2014-07-24 08:55 399 查看
setContentView和inflate区别:

setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来

一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这需LayoutInflater动态加载

< TextView

android:id="@+id/tview"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="ATAAW.COM"

/>

< Button

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/button"

android:text="按钮"

/>

在程序中动态加载以上布局。

LayoutInflaterflater = LayoutInflater.from(this);

View view =flater.inflate(R.layout.example, null);

获取布局中的控件。

button = (Button)view.findViewById(R.id.button);

textView =(TextView)view.findViewById(R.id.tview);

1、两种获得LayoutInflater的方法

a. 通过SystemService获得

LayoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLEATER_SERVICE);

b. 从给定的context中获取

Public static LayoutInflater from(Context context)

c. 两者的区别:实际上是一样的,源码

/**

* Obtains the LayoutInflater from the given context.

*/

public static LayoutInflater from(Context context) {

LayoutInflater LayoutInflater =

(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

if (LayoutInflater == null) {

throw new AssertionError("LayoutInflaternot found.");

}

return LayoutInflater;

}

2、 LayoutInflater.inflate()将Layout文件转换为View,专门供Layout使用的Inflater。虽然Layout也是View的子类,但在android中如果想将xml中的Layout转换为View放入.java代码中操作,只能通过Inflater,而不能通过findViewById()。

3、findViewById有两种形式

R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的组件,组件的id是xx(findViewById方法)。所有的组件id都能用R.id.xx来查看,但是组件不在setContentView()里面的layout中就无法使用,Activity.findViewById()会出现空指针异常

a. activity中的findViewById(int id)

b. View 中的findViewById(int id) view. findViewById(int id)

4、.不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: