随笔杂记

   :: 首页 :: 新随笔 ::  ::  :: 管理 ::

有时,Android系统控件无法满足我们的需求,因此有必要自定义View。具体方法参见官方开发文档:http://developer.android.com/guide/topics/ui/custom-components.html


一般来说,自定义控件都会去重写View的onMeasure方法,因为该方法指定该控件在屏幕上的大小。

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

onMeasure传入的两个参数是由上一层控件传入的大小,有多种情况,重写该方法时需要对计算控件的实际大小,然后调用setMeasuredDimension(int, int)设置实际大小。


onMeasure传入的widthMeasureSpec和heightMeasureSpec不是一般的尺寸数值,而是将模式和尺寸组合在一起的数值。我们需要通过int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size = MeasureSpec.getSize(widthMeasureSpec)得到尺寸。


mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, MeasureSpec.AT_MOST。


MeasureSpec.EXACTLY是精确尺寸,当我们将控件的layout_width或layout_height指定为具体数值时如andorid:layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸。


MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸。


MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式。


因此,在重写onMeasure方法时要根据模式不同进行尺寸计算。下面代码就是一种比较典型的方式:

@Override    
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    
    setMeasuredDimension(getMeasuredLength(widthMeasureSpec, true), getMeasuredLength(heightMeasureSpec, false));    
}    
    
    
private int getMeasuredLength(int length, boolean isWidth) {    
    int specMode = MeasureSpec.getMode(length);    
    int specSize = MeasureSpec.getSize(length);    
    int size;    
    int padding = isWidth ? getPaddingLeft() + getPaddingRight()    
            : getPaddingTop() + getPaddingBottom();    
    if (specMode == MeasureSpec.EXACTLY) {    
        size = specSize;    
    } else {    
        size = isWidth ? padding + mWave.length / 4 : DEFAULT_HEIGHT    
                + padding;    
        if (specMode == MeasureSpec.AT_MOST) {    
            size = Math.min(size, specSize);    
        }    
    }    
    return size;    
}  

posted on 2012-03-15 19:18 天宇恒星 阅读(30291) 评论(2)  编辑  收藏 所属分类: Android

评论

# re: Android中自定义View的MeasureSpec使用 2013-02-01 11:53 jeremy_sky
你好。mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, MeasureSpec.AT_MOST。既然三种模式对应不同的数值,那么为什么在源码中需要这个模式属性呢?比如:(Linearlayout.java 方法 measureVertical(int widthMeasureSpec, int heightMeasureSpec)部分源码 )
if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
} else {
int oldHeight = Integer.MIN_VALUE;

if (lp.height == 0 && lp.weight > 0) {
oldHeight = 0;
lp.height = LayoutParams.WRAP_CONTENT;
}
...
}
能帮我解释一下么?(主要是代码没看懂~~~)

  回复  更多评论
  

# re: Android中自定义View的MeasureSpec使用 2014-12-01 19:53 渣渣
heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0这个很明显是要判断权重weight,哎写自定义控件确实是个麻烦事,要考虑宽高,还要考虑padding,weight。  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: