public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
LayoutRes int resource:
當前需要顯示的layout資源ID
ViewGroup root:父view
boolean attachToRoot:
是否綁定到root view:resource是否作為root ViewGroup的Child
- root != null && attachToRoot = true
resource用自己的ViewGroup.LayoutParams 屬性 ,resource作為attachToRoot子view并添加到ViewGroup中惠勒,resource自己的LayoutParams屬性就不會失效。
返回View 是root 的ViewGroup。
- root != null && attachToRoot = true
- root != null && attachToRoot = false
resource用root的ViewGroup的屬性币励,resource 作為單獨View存在。
resource自己的LayoutParams(大小/位置)屬性就會失效珊拼。
返回的View 是resource View食呻。
- root != null && attachToRoot = false
- root == null && attachToRoot = true
無意義,因為root == null 會報異常
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
- root == null && attachToRoot = true
注意這里說的resource只是針對 resource自己的跟節(jié)點失效澎现。
如下面layout 》LinearLayout 的android:gravity屬性仅胞,而并非Button的android:layout_width
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
1和2的效果是一樣的
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
1.View view = inflater.inflate(R.layout.linearlayout, ll, true)
- View view = inflater.inflate(R.layout.linearlayout, ll, false)
ll.addView(view);
源碼如下
//當調(diào)用1.0 resource 會調(diào)用1.1
1.0 View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
1.1 View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
1.2 //創(chuàng)建匹配根目錄的布局參數(shù)
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
//設(shè)置臨時的布局參數(shù),temp為root的布局參數(shù)
temp.setLayoutParams(params);
}
1.3 if (root != null && attachToRoot) {
//當attachToRoot == true添加到root容器中
root.addView(temp, params);
}
參考:
三個案例帶你看懂LayoutInflater中inflate方法兩個參數(shù)和三個參數(shù)的區(qū)別