限制最大高度的 ListView
2017-05-11 13:36
537 查看
好记性不如烂笔头
问题描述: 最近遇这样的需求红色框里是一个 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方法即可
相关文章推荐
- ListView限制最大显示高度笔记
- Android-Dialog根据listview的数据量动态改变高度,并且有一个最大的高度
- 自定义可以设置最大高度的ListView
- 自定义可以设置最大高度的ListView
- 最大高度的listview
- C#中 form窗体的宽度和高度最大值限制
- 一个可以设置最大高度的ListView
- bootstrap modal插件弹出窗口如何限制最大高度,并且在内容过多时可以滚动显示
- 网页中限制图片的最大宽度和高度
- MFC,调整窗口大小限制大小,设置窗口的最大|最小宽度与高度
- img在IE6下用CSS限制最大高度、最大宽度
- 如何设置listview每个item高度
- IE中的最大最小宽度和高度
- 计算ListView的高度终极版,考虑到多行textview的情况
- android解决无法设定listview的item高度
- Android 限制启动应用最大使用内存,可供极限测试时使用
- 关于AbsListView item高度
- HDU 4616 树形DP + 限制求最大贡献值的路
- Android EditText输入最大长度限制如何给用户以友好的提示
- Linux下高并发socket最大连接数所受的各种限制