美文网首页Android应用开发那些事
LayoutInflater 的 inflate 方法的几个参数

LayoutInflater 的 inflate 方法的几个参数

作者: Cliper | 来源:发表于2020-01-11 16:02 被阅读0次
    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

      1. root != null && attachToRoot = true
        resource用自己的ViewGroup.LayoutParams 属性 ,resource作为attachToRoot子view并添加到ViewGroup中,resource自己的LayoutParams属性就不会失效。
        返回View 是root 的ViewGroup。
      1. root != null && attachToRoot = false
        resource用root的ViewGroup的属性,resource 作为单独View存在。
        resource自己的LayoutParams(大小/位置)属性就会失效。
        返回的View 是resource View。
      1. root == null && attachToRoot = true
        无意义,因为root == null 会报异常
        throw new InflateException("<merge /> can be used only with a valid "
        + "ViewGroup root and attachToRoot=true");

    注意这里说的resource只是针对 resource自己的跟节点失效。
    如下面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)

    1. View view = inflater.inflate(R.layout.linearlayout, ll, false)
      ll.addView(view);

    源码如下

    //当调用1.0 resource 会调用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            //创建匹配根目录的布局参数
                   params = root.generateLayoutParams(attrs);
                   if (!attachToRoot) {
                        //设置临时的布局参数,temp为root的布局参数
                         temp.setLayoutParams(params);
                    }
                    
    1.3            if (root != null && attachToRoot) {
                        //当attachToRoot == true添加到root容器中
                        root.addView(temp, params);
                    }
    
    

    参考:
    三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别

    相关文章

      网友评论

        本文标题:LayoutInflater 的 inflate 方法的几个参数

        本文链接:https://www.haomeiwen.com/subject/yqdpactx.html