LayoutInflater inflate参数详解

来源:互联网 发布:易语言端口数据到达 编辑:程序博客网 时间:2024/09/21 09:24

LayoutInflater

类概述:

实例化一个XML布局文件到相应的View对象,并不直接使用。使用getLayoutInflater()或getSystemService(String)来获取一个标准的布局填充器实例。可以勾子到当前的View对象,配置到您当前运行的设备上。

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

把指定的资源XML填充到一个分层的View对象中,如果发生错误,则抛出InflateException异常

参数解释:

resource:加载的XMl布局资源ID

root:生成的分层视图的父对象(如果attachToRoot为true),或者是一个简单的提供了一系列布局参数生成的Veiw对象(如果attachToRoot为false)

attachToRoot:是否要填充的分层视图要添加到父对象中,如果为false。ROOT内容仅仅是初始化,如果要使用,仍需要手动添加。

举例:

举个例子看一下
新建一个工程
工程包含两个xml文件
layout/main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”fill_parent”
    android:layout_height=”fill_parent”
    android:orientation=”vertical” >
    <TextView
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:text=”@string/hello” />
    <FrameLayout
        android:id=”@+id/ffff”
        android:layout_width=”match_parent”
        android:layout_height=”wrap_content”></FrameLayout>
</LinearLayout>
layout/ffff.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”vertical” >
    <CheckBox
        android:id=”@+id/checkBox1″
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:text=”CheckBox” />
</LinearLayout>
接下来看activity中怎么写的
这里分3中情况
first, no attachToRoot params
activity 中的部分代码,注意看红色部分
        setContentView(R.layout.main);
        ViewGroup v = (ViewGroup) findViewById(R.id.ffff);
        View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v);
 
布局结构图

Second, params attachToRoot is false
View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v, false);

发现没有了ffff.xml 中的内容
通过结构图查看,确实没有了

Third,
        ViewGroup v = (ViewGroup) findViewById(R.id.ffff);
        View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v, false);
        v.addView(vv);
运行结果

呵呵,又有了。
所以这个参数的作用就是,是否把选取的视图加入到root中。false 的意思就是不添加到root中。可能需要我们手动添加。

附注:例子转自http://www.189works.com/article-43331-1.html

原创粉丝点击