Why does calling getWidth() on a View in onResume() return 0?

扶醉桌前 提交于 2019-12-17 07:37:47

问题


Everything I've read says you can't call getWidth() or getHeight() on a View in a constructor, but I'm calling them in onResume(). Shouldn't the screen's layout have been drawn by then?

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

    populateData();
}

private void populateData() {
    LinearLayout test = (LinearLayout) findViewById(R.id.myview);
    double widthpx = test.getWidth();
}

回答1:


A view still hasn't been drawn when onResume() is called, so its width and height are 0. You can "catch" when its size changes using 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();
    }
});

For additional info take a look at Android get width returns 0.




回答2:


you have to wait that the the current view's hierarchy is at least measured before getWidth and getHeigth return something != 0. What you could do is to retrieve the "root" layout and post a runnable. Inside the runnable you should be able to retrieve width and height successfully

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


来源:https://stackoverflow.com/questions/22972022/why-does-calling-getwidth-on-a-view-in-onresume-return-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!