假设我们有在 XML 中声明的自定义 View ,并且我们覆盖了它的 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"
则 width 返回值 100。但是如果属性是 android:layout_width="match_parent"
或 android:layout_width="wrap_content"
然后它返回 -1 或 -2。那么在这种情况下,我们如何才能测量到该 View 的宽度呢?
最佳答案
使用
width = MeasureSpec.getSize(widthMeasureSpec);
关于android - layout_width 为 wrap_content 时如何获取自定义 View 的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26183314/