美文网首页RecycleView
Android—RecyclerView进阶(1)—Layout

Android—RecyclerView进阶(1)—Layout

作者: 东方未曦 | 来源:发表于2020-02-22 18:05 被阅读0次

    我的CSDN: ListerCi
    我的简书: 东方未曦

    RecyclerView是项目中使用最为频繁的控件之一,相关的知识点非常多,如果对RecyclerView的了解不够深入,那么在进行性能优化、自定义动画等工作时就会觉得力不从心。博主本人也有过多次这样的经历,因此下定决心要对RecyclerView相关的知识进行整理和学习,所以有了这一系列的博客。
    本系列将会对RecyclerView的内容和进阶使用进行介绍,包括布局加载、ItemDecoration、ItemAnimator、LayoutManager、ViewHoler重用和RecyclerView封装等内容,本文是第一篇,先来介绍一下ViewHolder视图的加载。话不多少,让我们开始吧。

    一、加载布局的三个方法

    我们一般通过LayoutInflater将布局文件加载到某个界面或者Layout中,加载布局文件时有如下3个方式。

    LayoutInflater.from(mContext).inflate(R.layout.item, null);
    LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
    LayoutInflater.from(mContext).inflate(R.layout.item, parent, true);
    

    我之前并没有特别关注它们参数的意义与作用,但是在用LayoutInflater为ViewHolder加载布局时,我发现了一点不同。
    我们来做个实验:分别通过这3个方式为RecyclerView的item加载布局,布局文件如下,item高度为150dp,内部有ImageView和TextView,来看下通过不同的方法为ViewHolder加载布局时的结果。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:gravity="center_vertical">
    
        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@mipmap/ic_launcher_round"/>
    
        <TextView
            android:id="@+id/item_test_inflate_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="16sp"
            android:layout_marginLeft="30dp"/>
    
    </LinearLayout>
    
    方式1: inflate(R.layout.item, null)
        @Override
        public TestInflateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext)
                    .inflate(R.layout.item_test_inflate, null);
            return new TestInflateViewHolder(view);
        }
    

    运行结果如下,显然与布局文件中设置的高度并不一致,也就是说,android:layout_height没有生效。

    运行结果1.png
    方式2: inflate(R.layout.item, parent, false)

    使用方法2时传入了onCreateViewHolder(...)提供的parent,attachToRoot属性设为false,这也是我们平时为item加载布局时最常用的方法。

        @Override
        public TestInflateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext)
                    .inflate(R.layout.item_test_inflate, parent, false);
            return new TestInflateViewHolder(view);
        }
    

    再来看运行结果,与布局文件完全一样。

    运行结果2.png
    方式3: inflate(R.layout.item, parent, true)

    再来尝试一下最后一个方法,运行之后程序闪退,日志如下。

    java.lang.IllegalStateException: 
    ViewHolder views must not be attached when created. 
    Ensure that you are not passing 'true' to the attachToRoot parameter of LayoutInflater.inflate(..., boolean attachToRoot)
    

    日志中说ViewHolder不能被attach到parent上,要我们保证LayoutInflater.inflate(..., boolean attachToRoot)中attachToRoot属性不能传true。

    实验做完,我们对LayoutInflater三种方式在加载ViewHolder时的作用也有了大概的了解。第1种方式虽然能加载布局,但是android:layout_width之类的属性不会生效;第2种方式传入了parent并设置attachToRoot为false之后,android:layout_width等属性就生效了;第3种方式不能用。

    虽然知道了结论,但是我们还是有很多问题:onCreateViewHolder()方法中传入的parent是什么?为什么不传入parent之前,高度等属性不生效?为什么attachToRoot不能设置为true?······为了解答这些问题,让我们一起去看一看源码。

    二、源码分析

    首先解答第1个问题,通过onCreateViewHolder(@NonNull ViewGroup parent, int viewType)中新建ViewHolder时,方法的第1个参数parent其实就是RecyclerView,也就是说,item的parent就是RecyclerView。

    下面的问题都是关于LayoutInflater的inflate(...)方法的,来看源码。

    // 实验中的第1种方式,实际调用下面的方法
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
    
    // 实验中的第2、3种方式,实际调用inflate(parser, root, attachToRoot)方法
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
            final Resources res = getContext().getResources();
            if (DEBUG) {
                Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                      + Integer.toHexString(resource) + ")");
            }
    
            View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
            if (view != null) {
                return view;
            }
            XmlResourceParser parser = res.getLayout(resource);
            try {
                return inflate(parser, root, attachToRoot);
            } finally {
                parser.close();
            }
        }
    

    看了源码之后我们发现3种方式是同源的,最后都会调用inflate(parser, root, attachToRoot)方法,其中的XmlResourceParser是用于解析xml文件的,来看该方法的源码。

        public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
            synchronized (mConstructorArgs) {
                final Context inflaterContext = mContext;
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                Context lastContext = (Context) mConstructorArgs[0];
                mConstructorArgs[0] = inflaterContext;
                View result = root;
    
                try {
                    advanceToRootNode(parser); // 找布局文件的根节点
                    final String name = parser.getName();
    
                    if (TAG_MERGE.equals(name)) {
                        // 如果根节点是<merge>······省略此处的代码
                    } else {
                        // temp就是xml文件的root view
                        final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                        ViewGroup.LayoutParams params = null;
    
                        if (root != null) {
                            // Create layout params that match root, if supplied
                            params = root.generateLayoutParams(attrs);
                            if (!attachToRoot) {
                                // 此处为第3种方式,为temp设置LayoutParams
                                // LayoutParams中包括layout_width等,就是这里设置的
                                temp.setLayoutParams(params);
                            }
                        }
    
                        rInflateChildren(parser, temp, attrs, true);
    
                        // 将temp通过addView的方式添加到root,也就是parent中
                        // 这种方式下,最后的返回值为root
                        if (root != null && attachToRoot) {
                            root.addView(temp, params);
                        }
                        // root为null或者attachToRoot为false时,返回的是temp
                        if (root == null || !attachToRoot) {
                            result = temp;
                        }
                    }
    
                } catch (XmlPullParserException e) {
                    // ......
                } catch (Exception e) {
                    // ......
                } finally {
                    mConstructorArgs[0] = lastContext;
                    mConstructorArgs[1] = null;
                    Trace.traceEnd(Trace.TRACE_TAG_VIEW);
                }
                return result;
            }
        }
    

    该方法的主体逻辑比较清晰,先是通过advanceToRootNode(parser)找到xml文件的根节点。方法中XmlPullParser.START_TAG就是指xml的开始节点,例如<LinearLayout>。对应的XmlPullParser.END_TAG就是指</LinearLayout>这样的结束节点。

        private void advanceToRootNode(XmlPullParser parser)
            throws InflateException, IOException, XmlPullParserException {
            // 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!");
            }
        }
    

    随后通过createViewFromTag(root, name, inflaterContext, attrs)方法创建了xml文件的根视图,在我们的例子中就是LinearLayout。再往下看,当传入的root不为null时,通过root.generateLayoutParams(attrs)生成LayoutParams,当attachToRoot为false时通过temp.setLayoutParams(params)为temp设置LayoutParams,此时layout属性才会生效,包括layout_width、layout_height、layout_margin等。

    之后通过rInflateChildren(parser, temp, attrs, true)递归地实例化整个xml文件中的view,此时temp的子View都已经被实例化了。

    接下来是比较重要的一步,当(root != null && attachToRoot),也就是用实验中的第3种方式加载布局时,会调用root.addView(temp, params)将temp添加到root中,并且最后返回的就是root。很显然这种方式无法用于新建ViewHolder,因为RecyclerView自己有一套重用ViewHolder的机制,不需要额外将View添加进去。而当(root == null || !attachToRoot)时,返回的结果是temp,也就是通过xml文件创建的视图。

    三、总结

    通过源码分析,布局加载的流程非常明确:
    如果你的View不需要LayoutParams,那么不用传入parent;
    如果你的View需要LayoutParams,那么必须传入一个parent,如果还要将View添加到parent中,那么attachToRoot为true,此时该方法的返回值为parent;如果不需要添加到parent中,则attachToRoot为false。

    相关文章

      网友评论

        本文标题:Android—RecyclerView进阶(1)—Layout

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