Skip to content Skip to sidebar Skip to footer

Why Does Calling Getwidth() On A View In Onresume() Return 0?

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

Solution 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 callsif(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.

Solution 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() {
     publicvoidrun() {
         LinearLayout test = (LinearLayout) findViewById(R.id.myview);
         double widthpx = test.getWidth();
     }
});

Post a Comment for "Why Does Calling Getwidth() On A View In Onresume() Return 0?"