RecyclerView 自定义设置最大高度

话不多说直接上代码


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"/>





如有问题请指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值