【问题标题】:Why getMeasuredWidth() returns 0? [duplicate]为什么 getMeasuredWidth() 返回 0? [复制]
【发布时间】:2017-06-13 02:46:07
【问题描述】:

在我的活动onCreate() 方法中,我创建了一个View 并将其宽度和高度硬编码为等于50。然后我调用measure 方法。之后,我希望 getMeasuredWidth() 返回 50。但它返回 0。

    View v = new View(this);
    v.setLayoutParams(new ViewGroup.LayoutParams(50, 50));

    final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    v.measure(spec, spec);
    final int w = v.getMeasuredWidth();
    Log.e("aaa", String.valueOf(w)); // output is 0

我做错了什么?如何强制计算测量视图的大小?我不想要,直到它被绘制,等等。

【问题讨论】:

  • 您可能需要再次阅读makeMeasureSpec的文档

标签: android android-layout


【解决方案1】:
private void measureDimension() {
    view.post(new Runnable() {
        @Override
        public void run() {
            int height = view.getMeasuredHeight();
            int width = view.getMeasuredWidth();

        }
    });
}

你可以在onCreate调用这个方法。

【讨论】:

  • 因为,这在 onCreate 或 onResume 期间无法完成,如副本所述。
猜你喜欢
  • 1970-01-01
  • 2011-01-09
  • 2014-08-17
  • 2012-08-09
  • 2019-12-15
  • 2018-04-14
  • 2017-02-10
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多