如何为RecyclerView设置最大高度?解决条目过多导致组件过高问题
当然可以给RecyclerView设置最大高度啦!刚好我之前也遇到过类似的需求,给你分享几个实用的方法,既能限制它的最大高度,又能让超出的条目正常滚动查看~
给RecyclerView设置最大高度的几种实现方式
方法一:直接在XML中设置maxHeight属性
这是最直接省心的方式,你只需要给RecyclerView添加android:maxHeight属性,同时开启垂直滚动条就行。这样当内容总高度小于你设置的最大高度时,RecyclerView会自适应内容高度;一旦超过最大高度,就会固定在设定高度,内部内容可以滚动查看。代码示例:
<android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recycler_goods" android:maxHeight="400dp" <!-- 这里替换成你需要的最大高度 --> android:scrollbars="vertical"/>
方法二:ConstraintLayout布局下用约束属性限制
如果你的RecyclerView是放在ConstraintLayout里,那可以用它自带的约束属性来控制最大高度,同样要把layout_height设为wrap_content,示例代码:
<android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recycler_goods" app:layout_constraintHeight_max="400dp" android:scrollbars="vertical" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent"/>
这种方式在ConstraintLayout体系下更灵活,还能配合其他布局约束一起调整位置。
方法三:自定义RecyclerView(适合动态调整高度的场景)
如果你的最大高度需要根据屏幕尺寸、业务逻辑动态计算,那自定义一个RecyclerView是更好的选择。重写onMeasure方法来限制最大高度,代码如下:
首先创建自定义RecyclerView类:
public class MaxHeightRecyclerView extends RecyclerView { private int maxHeight; public MaxHeightRecyclerView(Context context) { super(context); } public MaxHeightRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); initAttrs(context, attrs); } public MaxHeightRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAttrs(context, attrs); } private void initAttrs(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView); maxHeight = a.getDimensionPixelSize(R.styleable.MaxHeightRecyclerView_maxHeight, Integer.MAX_VALUE); a.recycle(); } @Override protected void onMeasure(int widthSpec, int heightSpec) { // 把高度测量模式设为AT_MOST,限制最大高度 heightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST); super.onMeasure(widthSpec, heightSpec); } }
然后在res/values/attrs.xml中添加自定义属性:
<resources> <declare-styleable name="MaxHeightRecyclerView"> <attr name="maxHeight" format="dimension"/> </declare-styleable> </resources>
最后在XML中使用这个自定义组件:
<com.yourpackage.MaxHeightRecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/recycler_goods" app:maxHeight="400dp" android:scrollbars="vertical"/>
这种方式能让你在代码里动态修改maxHeight值,适配更多复杂场景。
⚠️ 小提醒:不管用哪种方法,一定要把RecyclerView的android:layout_height设为wrap_content,这样它才会先尝试适应内容高度,再触发最大高度限制哦!
内容的提问来源于stack exchange,提问作者Mike Ma
相关产品推荐
相关产品推荐

