话不多说直接上代码
1.自定义RecyclerView,重写onMeasure方法,根据item个数及item高度去设置RecyclerView的高度
public class MaxHeightRecyclerView extends RecyclerView {
/**
* 默认最大高度
**/
private int maxHeight = 300;
public MaxHeightRecyclerView(Context context)
{
super(context);
init(context, null);
}
public MaxHeightRecyclerView(Context context, @Nullable AttributeSet attrs)
{
super(context, attrs);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs)
{
TypedArray a = attrs == null ? null : context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecycler);
if (a != null)
{
try
{
maxHeight = a.getInteger(R.styleable.MaxHeightRecycler_maxHeight, 300);
} finally
{
a.recycle();
}
}
// 设置的高度dp转成px
maxHeight = Utils.dip2px(maxHeight);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (getChildCount() > 0)
{
int height;
View child = getChildAt(0);
RecyclerView.LayoutParams params = (LayoutParams) child.getLayoutParams();
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
// item个数
int itemCount = getAdapter().getItemCount();
// item高度
int item = child.getMeasuredHeight() + getPaddingTop() + getPaddingBottom() + params.topMargin + params.bottomMargin;
// 把item的高度转成px
int max = itemCount * Utils.dip2px(item);
height = Math.min(max, maxHeight);
setMeasuredDimension(widthMeasureSpec, height);
} else
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
2.在attr.xml文件中加入:
<declare-styleable name="MaxHeightRecycler">
<attr name="maxHeight" format="integer" />
</declare-styleable>
3.在布局文件中设置最大高度
<com.xxx.MaxHeightRecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:maxHeight="400"/>
如有问题请指正