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

3

9

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();
}
Ranchod answered 9/4, 2014 at 19:18 Comment(0)
G
5

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.

Godart answered 9/4, 2014 at 19:25 Comment(0)
C
5

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();
     }
});
Conductance answered 9/4, 2014 at 19:26 Comment(1)
this works.... but if you could explain why this works it would be sweet!Mateusz
K
1

As previous answer stated - your view is not measured yet. Have a look at Android KTX - Kotlin extensions under Jetpack, especially this one:

View.doOnLayout((view: View) -> Unit)?)

This extension function makes sure that the provided action is executed once the VIew is laid out or, if it was already laid out, it will be called immediately.

https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#(android.view.View).doOnLayout(kotlin.Function1)

This article explains in detail how Views are measured, laid and drawn and what you as developer can do to ensure you get correct size of your View. It also goes over usually recommended solutions like View.post() and registering OnGlobalLayoutListener and explains what can go wrong when using them.

https://cheesecakelabs.com/blog/understanding-android-views-dimensions-set/

Keynesianism answered 3/3, 2022 at 13:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.