LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的使用

inflate(int resource, ViewGroup root, boolean attachToRoot)
第一个参数传入布局的资源ID,生成fragment视图,第二个参数是视图的父视图,通常我们需要父
视图来正确配置组件。第三个参数告知布局生成器是否将生成的视图添加给父视图。
root不为空的情况:
1.如果attachToRoot为true,就直接将这个布局添加到root父布局了,并且返回的view就是父布局
2.如果attachToRoot为false,就不会添加这个布局到root父布局,返回的view为resource指定的布局

root为空的情况:
View view = View.inflate(context, R.layout.button_layout, null);
其实等价于:LayoutInflater.from(this).layoutInflater.inflate(R.layout.button_layout, null);

那么root为不为空有什么影响呢?
1.如果root为null,attachToRoot将失去作用,设置任何值都没有意义。同时这个布局的最外层参数就没有效了
2.如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,
当该view被添加到父view当中时,这些layout属性会自动生效。
3.如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。

其实View必须存在于一个父布局中,这样layout_width和layout_height才会有效,
这也是为什么这两个属性叫作layout_width和layout_height,而不是width和height。
所以:inflate(int resource, ViewGroup root, boolean attachToRoot)的第二个参数不为空,resource的最外层布局参数才会有效,否则就无效了
例子:item的布局文件如下
<?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="100dp">

    <TextView
        android:id="@+id/textView"
        android:textSize="30sp"
        android:gravity="center"
        android:background="#ffcccc"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

如果我是这样加载这个布局:

View view= LayoutInflater.from(context).inflate(R.layout.recycler_item_layout,parent,false);

效果如下:  可见在item布局中设置的宽高都有效

如果我是这样加载布局:   

View view = View.inflate(context, R.layout.recycler_item_layout, null);

 效果图如下:   可见在item设置的宽高都无效,如果你在LinearLayout中设置宽高的长度为固定值100dp,这样也是没有效果的,但是如果是在TextView中设置宽高为固定值,这样是有效的

原因也就是layout_height是在父布局中的高度,你要是都没有父布局,它又怎么能知道你的match_parent是多大呢?,最后也就只能包裹内容了.

 

posted @ 2016-09-27 17:38  ts-android  阅读(3339)  评论(0编辑  收藏  举报