假设我们在 XML 中声明了我们的自定义视图,并且我们覆盖了它的 onMeasure() 方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Maximal length of line is width of this View
width = this.getLayoutParams().width;
如果设置了 XML 属性android:layout_width="100px"
,则宽度返回值 100。但如果属性是android:layout_width="match_parent"
或android:layout_width="wrap_content"
,则返回 -1 或 -2。那么在这种情况下,我们如何才能得到这个 View 的测量宽度呢?