答案是在父控件的onMeasure(int,int)中,而不是在自己的measure或者onMeasure中。
onMeasure(int,int){
......
int widthMeasureSpec = getChildMeasureSpec(int parentSpec, int padding, int childParamWidth)
......
child.measure(widthMeasureSpec, heightMeasureSpec);
}
从上述伪代码可看出要在ViewGroup的onMeasure中根据ViewGroup的measureSpec,padding和child的lp.width/heigh来确定子控件的measureSpec,而不是由子控件去计算自己的measureSpec。其中那个getChildMeasureSpec()方法是ViewGroup中用于计算子控件的measureSpec的一个方法,那里考虑了ViewGroup的measureSpec和padding和子控件的LayoutParams中的width去计算子控件的measureSpec。
其实子ViewGroup也可以自己去写一个得到子控件MeasureSpec的方法,因为不同布局的LayoutParams不一样,所以可能需要不一样的measureSpec计算方法,只要知道ViewGroup#getChildMeasureSpec的逻辑,可以很容易去定制有章可循的去自定义MeasureSpec的计算方法(要根据一定的逻辑和规则去改,不能随意定义,首先要明白SpecSize和SpecMode的含义)。