onMeasure在view中的作用:根据父容器传递跟子容器的大小要求来确定子容器的大小。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)的参数说明和MeasureSpec类的说明:
通过MeasureSpec这个类可以获取父View传递过来的一些信息,包括MODE、SIZE属性。这里做一下说明
- MODE:分为一下三种类别,
-
- AT_MOST:子容器可以是声明大小内的任意大小
- EXACTLY:父容器已经为子容器确定的大小,子容器应该遵守
- UNSPECIFIED:父容器对子容器没有做任何限制,子容器可以任意大小
- SIZE是父容器为子容器提供的大小
-
- 当MODE为AT_MOST时,SIZE大小不能大于父容器所能提供的最大值。
- 当MODE为EXACTLY时,SIZE为父容器提供的限制值。
- 当MODE为UNSPECIFIED时,大小为0,SIZE完全由子容器的大小决定。
代码事例:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mWidth = 0;
int mHeight = 0;
int width = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(heightMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if(widthMode == MeasureSpec.EXACTLY){//父类测量的值
mWidth = width;
}else{
mWidth = getNeedWidth() + getPaddingLeft() + getPaddingRight();
if(widthMode == MeasureSpec.AT_MOST){// 父类有固定的大小,如父类是match_parent,100dp
mWidth = Math.min(width, mWidth);
}
}
if(widthMode == MeasureSpec.EXACTLY){
mHeight = height;
}else{
mHeight = getNeedHeight() + getPaddingTop() + getPaddingBottom();
if(widthMode == MeasureSpec.AT_MOST){
mHeight = Math.min(mHeight, height);
}
}
setMeasuredDimension(mWidth, mHeight);
}
//定义需要的宽度,要转化为dp值
private int getNeedHeight() {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
}
//定义需要的高度,要转化为dp值
private int getNeedWidth() {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
}
注意:View的getMeasuredWidth、getWidth返回的值都是转化过的dp值.
getMeasuredWidth、getWidth的区别
一般在自定义控件的时候getMeasuredWidth/getMeasuredHeight它的赋值在View的 setMeasuredDimension中,所以有时可以在onMeasure方法中看到利用 getMeasuredWidth/getMeasuredHeight初始化别的参数。而getWidth/getHeight一直在onLayout 完成后才会被赋值。一般情况下,如果都完成了赋值,两者值是相同的