实验
在MainActivity中加载一个子布局:android
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:layout_height="match_parent" android:id="@+id/weChatPullView" android:orientation="vertical" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:id="@+id/loadLayoutBtn" android:text="加载布局" android:layout_width="110dp" android:layout_height="50dp" /> <RelativeLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> </RelativeLayout> </RelativeLayout>
子布局:函数
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/testBtn" android:text="Button" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
四种能够成功加载子布局的状况:源码分析
LayoutInflater inflater = getLayoutInflater(); inflater.inflate(R.layout.test_layout,container,true);
LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.test_layout,null); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); container.addView(view,params);
LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.test_layout,container,false); container.addView(view);
4.两个参数时 , 第三个参数默认是true布局
LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.test_layout,container);
没法加载子布局的状况:code
LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.test_layout,null); container.addView(view);
分析实验
inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
主要分析第二个和第三个参数的做用:xml
-
从上面的实验来看,若是没有第二个参数(为null),咱们就须要设置要加载的view的宽和高,才能实现成功加载到父布局中。utf-8
-
第三个参数为true的时候,自动加载该view到root布局中去,不须要调用addView这个函数,说明第三个参数的做用是判断是否加载布局到父布局中去get
源码分析
if (root != null) { if (DEBUG) { System.out.println("Creating params from root: " + root); } // Create layout params that match root, if supplied params = root.generateLayoutParams(attrs); if (!attachToRoot) { // Set the layout params for temp if we are not // attaching. (If we are, we use addView, below) temp.setLayoutParams(params); } }
params = root.generateLayoutParams(attrs); 能够看出来源码
若是 root 为空 ,那么无论 须要 被加载的view布局参数 是怎样的 ,都不能计算出来他的布局参数,也就没法经过parent.addView加载到布局中去it
大部分状况下,咱们都是使用 inflate(id,container,false) 这种方式去加载子view;DialogFragment不须要container去生成布局参数,第二个参数为null