自定义可设置MaxHeight的RecyclerView
引言
在实际工作中,可能会遇到这样一种需求,在一个列表下面紧跟一个按钮,就像垂直的LinearLayout中,先是一个RecyclerView然后跟着一个button,但是这样布局会有一个问题,当RecyclerView的内容超过一屏时,这个button就被移到屏幕外了,看不见了。如果用相对布局呢,把button定在底部,这也显然不是那么完美,因为当recyclerView的内容不足一屏时,button还是在屏幕底部,不会紧跟在列表下面,显得有点突兀。此时我们很自然会想到有没有类似maxHeight这样的属性,给RecyclerView设置一个最大高度,这样就能达到跟随在RecyclerView底部的效果了。不过很遗憾,sdk并没有提供这样一个属性,如果要达到这个效果就只能自定义RecyclerView了。下面来说说具体做法:
一、用代码设置RecyclerView的最大高度
首先新建一个Class,继承RecyclerView。
/**
* 可以设置最大高度的recyclerView,在布局里使用 maxHeight属性指定最大高度
*
* @author Huangming 2019/4/8
*/
public class MaxHeightRecyclerView extends RecyclerView {
private int mMaxHeight;
/**
* 设置最大高度
*
* @param maxHeight 最大高度 px
*/
public void setMaxHeight(int maxHeight) {
this.mMaxHeight = maxHeight;
// 重绘 RecyclerView
requestLayout();
}
public MaxHeightRecyclerView(Context context) {
super(context);
}
public MaxHeightRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MaxHeightRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(contex