RecyclerView 设置最大高度

2,621 阅读1分钟

场景在: 在dialog有一个RecyclerView的列表,如果大于7条的话,将高度固定便于滑动,如果小于7条的话高度是item的高度*个数

实现方式:

  1. 自定义RecyclerView,重写里面的onMeasure方法:
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_maxHeight, 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);
    }
}

自定义属性:

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

xml添加:

app:maxHeight="400dp"
  1. 使用约束布局

    布局文件关键代码:

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/view_constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_height="0dp"
        app:layout_constraintHeight_default="wrap"
        app:layout_constraintHeight_max="350dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

代码

ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(view_constraintLayout);
constraintSet.constrainMaxHeight(R.id.recycler_view,ScreenUtil.dip2px(350));
TransitionManager.beginDelayedTransition(view_constraintLayout);
constraintSet.applyTo(view_constraintLayout);