您的位置:首页 > 其它

自定义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):根据提供的大小值和模式创建一个测量值(格式)


值得阅读
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: