天天看點

Android中當item數量超過一定大小時,将RecyclerView高度固定

重寫LayoutManger的onMeasure方法,這種方式可以擷取到各個item的不同高度,進而可以設定變動的高度。

在使用這種方式時,有一點需要注意的是,不要将RecyclerView的android:layout_height屬性設定為wrap_content,保險點可以設定成四個item的高度dp值,不然是不會成功的。

小于四高度自适應,大于四高度就固定

recyclerView.setLayoutManager(new LinearLayoutManager(this) {
    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        int count = state.getItemCount();

        if (count > 0) {
            if(count>4){
                count =4;
            }
            int realHeight = 0;
            int realWidth = 0;
            for(int i = 0;i < count; i++){
                View view = recycler.getViewForPosition(0);
                if (view != null) {
                    measureChild(view, widthSpec, heightSpec);
                    int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                    int measuredHeight = view.getMeasuredHeight();
                    realWidth = realWidth > measuredWidth ? realWidth : measuredWidth;
                    realHeight += measuredHeight;
                }
                setMeasuredDimension(realWidth, realHeight);
            }
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);
        }
    }
});
           

或者重寫RecyclerView加一個最大高度的屬性MaxHeightRecyclerView:

public class MaxHeightRecyclerView extends RecyclerView {
    private int mMaxHeight;
    public MaxHeightRecyclerView(Context context) {
        super(context);
    }
    public MaxHeightRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }
    public MaxHeightRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
    }
    private void initialize(Context context, AttributeSet attrs) {
        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView);
        mMaxHeight = arr.getLayoutDimension(R.styleable.MaxHeightRecyclerView_max_height, mMaxHeight);
        arr.recycle();
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
           

然後在values檔案夾下建立一個attrs.xml檔案加入如下屬性:

<declare-styleable name="MaxHeightRecyclerView">
        <attr name="max_height" format="dimension" />
    </declare-styleable>
           

使用:

<com.android.view.MaxHeightRecyclerView
        android:id="@+id/rv_accountList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:max_height="152dp"/>