【问题标题】:How to get custom View's width when layout_width is wrap_content?当 layout_width 为 wrap_content 时如何获取自定义 View 的宽度?
【发布时间】:2014-11-28 18:28:29
【问题描述】:

假设我们在 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",则 width 返回值 100。但如果属性为 android:layout_width="match_parent"android:layout_width="wrap_content",则返回 -1 或 -2。那么在这种情况下我们如何获得这个 View 的测量宽度呢?

【问题讨论】:

    标签: android layout view width onmeasure


    【解决方案1】:

    使用

    width = MeasureSpec.getSize(widthMeasureSpec);
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 2021-06-04
      • 2023-03-23
      • 2013-04-07
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      相关资源
      最近更新 更多