方法 inflate(int resource, ViewGroup root, boolean attachToRoot) 中,前連個參數都好理解,我比較費解的是第3個參數。
文檔中的解釋是:Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.
舉個例子看一下
新建一個工程
工程包含兩個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中。可能需要我們手動添加。