RecyclerView在ScrollView中使用wrap_content

RecyclerView如果在ScrollView中使用wrap_content,那么有可能会出现高度为0的情况,为了解决这个问题,我们要手动测量高度并且设置高度,RecyclerView测量工作都是交个LayoutManager的,所以我们要从LayoutManager下手。

以LinearLayoutManager为例子,重写onMeasure方法:

public class AutoSizeLayoutManager extends LinearLayoutManager{

    public AutoSizeLayoutManager(Context context) {
        super(context);
    }

    public AutoSizeLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public AutoSizeLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }



    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        int itemCount = getItemCount();
        if (itemCount == 0) {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
            return;
        }

        //测量每个item,高度相加
        int measuredWidth = 0;
        int measuredHeight = 0;
        for (int i = 0; i < itemCount; i++) {
            View view = recycler.getViewForPosition(i);
            if (view != null) {
                measureChild(view, widthSpec, heightSpec);
                measuredWidth += view.getMeasuredWidth();
                measuredHeight += view.getMeasuredHeight();
            }
        }

        //if (!isAutoWidth){//使用原来的宽度
        // measuredWidth = View.MeasureSpec.getSize(widthSpec);
        //}
        //if (!isAutoHeight){//使用原来的高度
        // measuredHeight = View.MeasureSpec.getSize(heightSpec);
        //}
        setMeasuredDimension(measuredWidth, measuredHeight);

    }
}

声明

原创文章,欢迎转载,请保留出处。
有任何错误、疑问或者建议,欢迎指出。
我的邮箱:[email protected]

你可能感兴趣的:(android,高度,宽度,自适应)