最近在看一些android的文档,当看到android如何自定义一个view的时候,有些不解的地方。
官方文档重写的onMeasure如下:
http://developer.android.com/training/custom-views/custom-drawing.html@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   // Try for a width based on our minimum
   int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
   int w = resolveSizeAndState(minw, widthMeasureSpec, 1);   // Whatever the width ends up being, ask for a height that would let the pie
   // get as big as it can
   int minh = MeasureSpec.getSize(w) - (int)mTextWidth + getPaddingBottom() + getPaddingTop();
   int h = resolveSizeAndState(MeasureSpec.getSize(w) - (int)mTextWidth, heightMeasureSpec, 0);   setMeasuredDimension(w, h);
}问题如下:
1. 计算宽度我还可以理解,但是计算minh的时候,怎么跟宽度扯上关系了?
   我个人理解计算高度的时候,也可以采取类似于计算宽度的方法:
   int minh = getPaddingTop() + getPaddingBottom() + getSuggestedMinimumHeight();
   int h = resolveSizeAndState(minw, widthMeasureSpec);2. MeasureSpec.getSize(w)又是个神马东西?
   根据API文档,MeasureSpec.getSize(w)的参数应该是一个measureSpec, 也就是类似于widthMeasureSpec这类的,这里为  什么能将前面得到的宽度w传进去?希望各位朋友能帮我解惑下。

解决方案 »

  1.   

    这个onMeasure我也不知道,同求。
      

  2.   

    翻墙下了这个例子的源码来看了下,原来是google在网页上写错了。坑爹啊~~~
    源码中正确的代码为:    @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            // Try for a width based on our minimum
            int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();        int w = Math.max(minw, MeasureSpec.getSize(widthMeasureSpec));        // Whatever the width ends up being, ask for a height that would let the pie
            // get as big as it can
            int minh = (w - (int) mTextWidth) + getPaddingBottom() + getPaddingTop();
            int h = Math.min(MeasureSpec.getSize(heightMeasureSpec), minh);        setMeasuredDimension(w, h);
        }