RecyclerView的onmeasure方法

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容