为什么getMeasuredWidth()返回0?

时间:2017-01-27 12:07:23

标签: android android-layout

在我的活动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

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

1 个答案:

答案 0 :(得分:2)

private void measureDimension() {
    view.post(new Runnable() {
        @Override
        public void run() {
            int height = view.getMeasuredHeight();
            int width = view.getMeasuredWidth();

        }
    });
}

您可以在onCreate

中调用此方法