天天看点

inflate 使用对比

LayoutInflater inflater = LayoutInflater.from(context);
View inflate1 = View.inflate(getActivity(), R.layout.test_main, null);
View inflate2 = inflater.inflate(R.layout.test_main, null);
View inflate3 = inflater.inflate(R.layout.test_main, null, false); // false 无意义
View inflate4 = inflater.inflate(R.layout.test_main, null, true);  // true 无意义
View inflate5 = inflater.inflate(R.layout.test_main, container, true);
View inflate6 = inflater.inflate(R.layout.test_main, container, false);
           
1.View inflate1 = View.inflate(getActivity(), R.layout.test_main, null);
调用了以下方法,本质还是同下面 inflate2 一样
      
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
    LayoutInflater factory = LayoutInflater.from(context);
    return factory.inflate(resource, root);
}
           
2.View inflate2 = inflater.inflate(R.layout.test_main, null);
调用了以下方法,本质还是同下面 inflate3 一样
      
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    return inflate(resource, root, root != null);
}
           
3.View inflate3 = inflater.inflate(R.layout.test_main, null, false);
4.View inflate4 = inflater.inflate(R.layout.test_main, null, true);
解析并加载 return view, 如果root为null,attachToRoot将失去作用,设置任何值都没有意义
5.View inflate5 = inflater.inflate(R.layout.test_main, container, true);
加载view到container
6.View inflate6 = inflater.inflate(R.layout.test_main, container, false);
将布局外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。      

推荐郭大神的分析和结论:

1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。

2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。

4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。