限制最大高度的 ListView

好记性不如烂笔头

问题描述: 最近遇这样的需求

红色框里是一个 ListView 但是其 item 数量不固定, 本来是用的 wrap_content 来限制高度.但是遇到了特殊情况:在某些小屏幕手机上,若 item 过多. 小弹窗会超过屏幕.因此需要一个能限制最大高度的 ListView .当实际高度小于最大高度就显示 wrap_content 效果,当大于最大高度就限定为最大高度,多出的部分需要 ListView 滑动展示

如图


解决思路 重写 ListView 的 onMeasure 方法


具体步骤
1.1新建 ListView 子类 ConstraintHeightListView

public class ConstraintHeightListView extends ListView {
    private float mMaxHeight = 100;//默认100px

    public ConstraintHeightListView(Context context) {
        this(context, null);
    }

    public ConstraintHeightListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ConstraintHeightListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ConstraintHeightListView, 0, defStyleAttr);
        int count = array.getIndexCount();
        for (int i = 0; i < count; i++) {
            int type = array.getIndex(i);
            if (type == R.styleable.ConstraintHeightListView_maxHeight) {
            //获得布局中限制的最大高度
                mMaxHeight = array.getDimension(type, -1);
            }
        }
        array.recycle();
    }

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取lv本身高度
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        //限制高度小于lv高度,设置为限制高度
        if (mMaxHeight <= specSize && mMaxHeight > -1) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(Float.valueOf(mMaxHeight).intValue(),
                    MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

1.2 自定义属性
在 项目的 style 文件中加上自定义属性名

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

1.3在布局中引用
如下

备注

实现1.1–1.3的步骤就可以了
如果不想自定义属性那就更简单(适用性稍差),可以只用步骤1.1 给定mMaxHeight 重写onMeasure 方法即可

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值