美文网首页
RecyclerView的onmeasure方法

RecyclerView的onmeasure方法

作者: 陈萍儿Candy | 来源:发表于2021-01-19 14:41 被阅读0次

onMeasur方法中经过是否有LayoutManager的对象一般都是走了这个方法去测量宽高,defaultOnMeasure,源码如下:

/**
     * An implementation of {@link View#onMeasure(int, int)} to fall back to in various scenarios
     * where this RecyclerView is otherwise lacking better information.
     */
    void defaultOnMeasure(int widthSpec, int heightSpec) {
        // calling LayoutManager here is not pretty but that API is already public and it is better
        // than creating another method since this is internal.
        final int width = LayoutManager.chooseSize(widthSpec,
                getPaddingLeft() + getPaddingRight(),
                ViewCompat.getMinimumWidth(this));
        final int height = LayoutManager.chooseSize(heightSpec,
                getPaddingTop() + getPaddingBottom(),
                ViewCompat.getMinimumHeight(this));

        setMeasuredDimension(width, height);
    }

最终又都调用了layoutmanager的chooseSize方法,源码如下

public static int chooseSize(int spec, int desired, int min) {
            final int mode = View.MeasureSpec.getMode(spec);
            final int size = View.MeasureSpec.getSize(spec);
            switch (mode) {
                case View.MeasureSpec.EXACTLY:
                    return size;
                case View.MeasureSpec.AT_MOST:
                    return Math.min(size, Math.max(desired, min));
                case View.MeasureSpec.UNSPECIFIED:
                default:
                    return Math.max(desired, min);
            }
        }

案例分析:
如果recyclerView的外面包裹的viewgroup设置为wrapContent,recyclerview也是wrapcontent,recyclerview的height测量高度为0,recyclerview无法展示,此时给recyclerView或其外面的viewgroup设置一个固定的高度,recyeclerview就可以测量出自己的高度,正常展示;

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="500dp"> // 1.给relativeLayout设置固定高度或者matchparent

    <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />// 给recyclerview设置固定高度或者matchparent

</RelativeLayout>

详细的解析onMeasure源码文章:https://blog.csdn.net/qq_36391075/article/details/82022305

相关文章

网友评论

      本文标题:RecyclerView的onmeasure方法

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