自定义GridView
2016-01-05 11:18
232 查看
自定义GridView根据item个数填充显示(同样适用于ListView)
在一些布局页面上经常会有滑动控件的嵌套比如:ScrollView和GridView或者ListView。由于Item的个数不确定,这也就决定了GridView或者ListView的高度不确定。为了解决这个问题我们需要做的就是重写View继承GridView或者ListView,然后重写onMeasure()方法即可。废话不多说,直接上代码,可以拿去直接用.public class MyGridView extends GridView{ public MyGridView(Context context, AttributeSet attrs) { this(context, attrs,0); } public MyGridView(Context context) { this(context,null); } public MyGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
可以看到整个代码就对onMeasure方法进行了重写,其中重要的就是MeasureSpec这个类.
看一下MeasureSpec的源码(英语写的好高级,看了下大概意思)
MeasureSpec封装了父布局对传递给子布局的布局要求,MeasureSpec由大小和模式组成. MeasureSpec有三种模式 1.EXACTLY * <dt>EXACTLY</dt> * <dd> * The parent has determined an exact size for the child. The child is going to be * given those bounds regardless of how big it wants to be. * </dd> 大概意思是说这种模式一般是设置了确切的值或者MATCH_PARENT 2.AT_MOST * <dt>AT_MOST</dt> * <dd> * The child can be as large as it wants up to the specified size. 这种模式表示子布局限制在一个最大值内,一般是WRAP_CONTENT 3.UNSPECIFIED * <dt>UNSPECIFIED</dt> * <dd> * The parent has not imposed any constraint on the child. It can be whatever size * it wants. 表示子布局想要多大,就给多大 另外从MeasureSpec源码中可以看到三个方法 1.static int getMode(int measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一) 2.static int getSize(int measureSpec):根据提供的测量值(格式)提取大小值 3.static int makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)
值得阅读
相关文章推荐
- Android文件读写注意点
- 非技术:评论关于12306功能问题
- 两年前端路回顾
- 使用位图字体工具BMFont从图片生成自定义字体
- java 解压压缩文件
- ML&DL&CV知名期刊会议
- Windows10使用MySQL5.7zip包
- MyEclipse8.5注册码有效期2018年
- Google Map开发系列(五)——怎样在你的网页里嵌入地图
- C# 用OO来实现超市的购买结账
- 基于S5pv210流媒体server的实现之网络摄像头(by liukun321 咕唧咕唧)
- 进程和线程
- hadoop杂记-为什么会有Map-reduce v2 (Yarn)
- MySQL-慢查询日志
- Mysql多表查询
- 64位redhat编译执行32位c++程序(redhat安装centos源)
- Shell bash 脚本语法
- CC2538之TinyOS例程实验:8-RPL(roll)路由实验
- iOS开发系列--让你的应用“动”起来
- 一个js文件引入其他多个常用js文件的使用方法及适用范围