为什么在onResume()的View上调用getWidth()返回0?

And*_*rew 9 android android-layout activity-lifecycle android-view android-viewtreeobserver

我读过的所有内容都说您不能在构造函数中调用getWidth()getHeight()在上调用View,但我在中调用它们onResume()。届时是否应该绘制屏幕布局?

@Override
protected void onResume() {
    super.onResume();

    populateData();
}

private void populateData() {
    LinearLayout test = (LinearLayout) findViewById(R.id.myview);
    double widthpx = test.getWidth();
}
Run Code Online (Sandbox Code Playgroud)

Oni*_*nik 5

onResume()调用时仍未绘制视图,因此其宽度和高度为 0。您可以使用以下命令“捕捉”其大小发生变化的情况OnGlobalLayoutListener()

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {

        // Removing layout listener to avoid multiple calls
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }
        else {
            yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }

        populateData();
    }
});
Run Code Online (Sandbox Code Playgroud)

有关其他信息,请查看Android get width returns 0

  • 谢谢,我喜欢可以剪切和粘贴的答案。 (2认同)

Bla*_*elt 5

你必须等待当前视图的层次结构至少在之前被测量getWidthgetHeigth返回一些东西!= 0。你可以做的是检索“根”布局并发布一个可运行的。在 runnable 中,您应该能够成功检索宽度和高度

root.post(new Runnable() {
     public void run() {
         LinearLayout test = (LinearLayout) findViewById(R.id.myview);
         double widthpx = test.getWidth();
     }
});
Run Code Online (Sandbox Code Playgroud)