getWidth() 方法和 getMeasureWidth() 方法的区别

首先 getMeasureWidth() 方法在 measure() 过程结束后就可以获取到了,而 getWidth() 方法要在 layout() 过程结束后才能获取到。另外 getMeasureWidth() 方法中的值是通过 setMeasuredDimension() 方法来进行设置的,而 getWidth() 方法中的值则是通过视图右边的坐标减去左边的坐标计算出来的。

观察 SimpleLayout 中 onLayout() 方法的代码,这里给子视图的 layout() 方法传入的四个参数分别是 0,0,childView.getMeasuredWidth() 和 childView.getMeasuredHeight() ,因此 getWidth() 方法得到的值就是 childView.getMeasuredWidth() - 0 = childView.getMeasuredWidth(),所以此时 getWidth() 方法和 getMeasuredWidth() 得到的值就是相同的。

1
2
3
4
5
6
7
@Override  
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (getChildCount() > 0) {
View childView = getChildAt(0);
childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
}
}

但如果你将 onLayout() 方法中的代码进行如下修改:

1
2
3
4
5
6
7
@Override  
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (getChildCount() > 0) {
View childView = getChildAt(0);
childView.layout(0, 0, 200, 200);
}
}

这样 getWidth() 方法得到的值就是 200 - 0 = 200,不会再和 getMeasuredWidth() 的值相同了。当然这种做法充分不尊重 measure() 过程计算出的结果,通常情况下是不推荐这么写的。 getHeight() 与 getMeasureHeight() 方法之间的关系同上,就不再重复分析了。


参考资料

Android视图绘制流程完全解析,带你一步步深入了解View(二)