LayoutInflater inflate参数详解

LayoutInflater

类概述:html

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

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

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

参数解释:布局

resource:加载的XMl布局资源IDthis

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

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

举例:xml

举个例子看一下htm

新建一个工程对象

工程包含两个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

  • 0

相关文章
相关标签/搜索