好记性不如烂笔头
问题描述: 最近遇这样的需求
红色框里是一个 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
方法即可