美文网首页
解决布局加载那些奇奇怪怪的事🤣

解决布局加载那些奇奇怪怪的事🤣

作者: 糖葫芦_倩倩 | 来源:发表于2021-07-15 15:46 被阅读0次

    1.引言

    Android中,我们需要动态添加View的时候,通常会先去加载布局,那加载布局的方式一般有以下两种方式:

    //第一种方式
    View.inflate(this,R.layout.xx,null);
    //第二种方式
    LayoutInflater.from(this).inflate(R.layout.xx,null,false);
    

    一般有经验的人会跟你说,用第二种方式靠谱,那如果你偏偏要用第一种呢,也不是不可以,用不好的话,就会出现一些奇奇怪怪的事:

    2. 怪事一

    我现在有一个 Activity 类的布局,里面只有一个LInearLayout ,我需要动态往这个LinearLayout 中添加一个 TextView, 这个TextView 我设置了高度为 100dp, 背景颜色设置为 红色,直接看下面代码:

    //activity_activity_inflate
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/ll_container"
        android:orientation="vertical" />
    ___________________________________________________________
    //item_child
    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="#ff5232"
        android:text="Hello world"
        android:textColor="#ffffff"
        android:layout_width="match_parent"
        android:id="@+id/tv"
        android:layout_height="100dp" />
    
    

    动态添加 TextView

    LinearLayout ll_container = findViewById(R.id.ll_container);
    View child = View.inflate(this,R.layout.item_child,null);
    ll_container.addView(child);
    
    

    运行结果图:

    image

    怪事来了,👉我们明明设置 TextView 的高度为 100dp , 怎么就显示 wrap_content 呢❔这里我们记录一下,为怪事1.

    3.怪事二

    我们修改一下我们动态添加的代码:

    LinearLayout ll_container = findViewById(R.id.ll_container);
    View child = View.inflate(this,R.layout.item_child,ll_container);
    ll_container.addView(child);
    
    

    第三个参数把 null 修改为 ll_container , 再次运行:

    oh..mygod,程序直接崩溃了,错误日志信息如下:

    The specified child already has a parent. You must call removeView() on the child's parent first.
    
    

    当然在我们使用RecyclerViewadapter 里,也会要加载布局,使用不当,也是会出现所写非所得的效果,那到底是怎么回事呢?

    这里假设你对布局加载的流程有一定了解,无论是哪种布局加载方式,最终都会调用到这里:

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        ...
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
    
    

    LayoutInflater#inflate 方法,三个参数的。继续跟进的话就是 inflate 方法,以下这个方法是我们重点关注的,我只留下重要代码:

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
            ....
            View result = root;//-------------------1
    
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
    
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
    
                final String name = parser.getName();
    
                if (DEBUG) {
                    System.out.println("**************************");
                    System.out.println("Creating root view: "
                            + name);
                    System.out.println("**************************");
                }
                ...
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
    
                    ViewGroup.LayoutParams params = null;
    
                    if (root != null) {//---------2
                        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);
                        }
                    }
                    rInflateChildren(parser, temp, attrs, true);
                    
                    if (root != null && attachToRoot) {//---------3
                        root.addView(temp, params);
                    }
    
                    if (root == null || !attachToRoot) {//---------4
                        result = temp;
                    }
                }
            return result;
        }
    
    

    注释1:将root 赋值为result , 用于返回的;

    注释2:root!=null,就会解析我们在 xml中设置的属性值转换为 :params , 同时 attachToRoot 如果为 false的话,就可以进入if条件里,就可以为我们从xml解析出来的temp设置LayoutParams 了。

    PS:这里需要主要的是,我们通过 final View temp = createViewFromTag(root, name, inflaterContext, attrs); 这句话只是得到一个 View ,如果xml中写的TextView 解析出来就是一个 TextViewtemp ,没有携带 宽高,边距等信息。

    注释3:root!=null && attachToRoot(true) ,我们xml中解析出的View,会自动帮我们addroot里,并且是携带LayoutParams.

    注释4:root==null || !attachToRoot ,把 result 修改为 temp , xml解析出来的 ,注意这时候是没有任何 LayoutParams 的,这也就意味着我们在xml 中设置的属性值会失效。

    👉回顾一下,我们之前遇到的问题。
    我们通过:

    LinearLayout ll_container = findViewById(R.id.ll_container);
    View child = View.inflate(this,R.layout.item_child,null);
    ll_container.addView(child);
    
    

    这种方式addView. 对应到源码里是怎么样的呢?
    跟进去层层调用就到了这里:

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
    

    我们传入的第三个参数为null ,就意味着:

    return inflate(resource, null, false);
    

    来重新对应一下,inflate 的三个参数:

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    

    也就是意味着:root == null ,attachToRoot = false.
    换一种写法:

    View.inflate(this,R.layout.item_child,null);
    等价于
    设置了:root == null ,attachToRoot = false

    根据我们前面的分析,只有root!=null 的时候,才会去给 params 赋值。

    if (root != null) {
         params = root.generateLayoutParams(attrs);
        ...
    }
    

    看到了吧,接下来就是 进入注释4那个代码了:

    if (root == null || !attachToRoot) {//---------4
         result = temp;
    }
    
    

    temp 返回了,这个 temp 是啥,就是我们从xml中解析出的View(没有任何params).

    👉 第二个问题,为什么我们那么写崩溃报错,把之前的拿来再看一下:

    LinearLayout ll_container = findViewById(R.id.ll_container);
    View child = View.inflate(this,R.layout.item_child,ll_container);
    ll_container.addView(child);
    

    与第一次不同的是,我传入了 ll_container , 就意味着什么?意味着我们的 root!=null && attachToRoottrue了。
    这样的话,就进入了我们注释3处 的代码了:

     if (root != null && attachToRoot) {//---------3
           root.addView(temp, params);
     }
    

    rootll_container , 系统自动帮我们 addView 添加进去了,
    root.addView(temp, params); 等价于ll_container.addView(temp,params) ;
    return root了。

    我们需要注意的是:

    View child = View.inflate(this,R.layout.item_child,ll_container);
    

    这句话本身并不会让程序崩溃,真正让程序崩溃的是:

    ll_container.addView(child);
    

    根据前面的分析,此时我们的 child 已经被添加进这个ll_container 里了,你如果再把 child 添加到另外一个容器里,系统是不允许的,一个 child 只能有一个 paraent.
    所以当你执行那句代码的时候,系统这里有判断:

    image
    看到了吧,所以我们想把 child 添加到 ll_container 中,只需要:
    View.inflate(this,R.layout.item_child,ll_container);
    

    写这一行足矣,下面那行就属于画蛇添足了。
    好了,今天分享就到此结束了,有问题,评论区见~

    相关文章

      网友评论

          本文标题:解决布局加载那些奇奇怪怪的事🤣

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