每个View中都有一个测量绘制控件大小的方法onMeasure(int widthMeasureSpec, int heightMeasureSpec) ,该方法用于初始化控件所占的区域:
摘自SlidingDrawer.java,仅作参考说明onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //onMeasure方法传入的两个参数widthMeasureSpec, heightMeasureSpec,其单位为dp或dip int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); //这里判断单位是dp或dip,有或者其他的单位类型 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); //将单位转为px int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions"); } // final View handle = mHandle; measureChild(handle, widthMeasureSpec, heightMeasureSpec); if (mVertical) { int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset; mContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); } else { int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset; mContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY)); } //最后绘制父控件的大小 setMeasuredDimension(widthSpecSize, heightSpecSize); //super.onMeasure(widthMeasureSpec, heightMeasureSpec)原型则是下面这样写的: //setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), // getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }