If I call getMeasuredWidth() or getWidth() for layout in onResume they return 0

mobiledev Alex picture mobiledev Alex · Aug 4, 2011 · Viewed 33.8k times · Source

If I call getMeasuredWidth() or getWidth() for layout in onResume they returns 0. I think that view it's not drawn yet in this moment.

Also I think that I need to put getMeasuredWidth() or getWidth() in callback method called after layout is drawn and view measurements are known. What android callback method should I use?

Answer

Adorjan Princz picture Adorjan Princz · Jan 20, 2013

You cannot use the width/height/getMeasuredWidth/getMeasuredHeight on a View before the system renders it (typically from onCreate/onResume).

Simple solution for this is to post a Runnable to the layout. The runnable will be executed after the View has been laid out.

BoxesLayout = (RelativeLayout) findViewById(R.id.BoxesLinearLayout);
BoxesLayout.post(new Runnable() {
    @Override
    public void run() {
        int w = BoxesLayout.getMeasuredWidth();
        int h = BoxesLayout.getMeasuredHeight();

        ...
    }
});