Search code examples
androidlayoutmeasurement

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


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?


Solution

  • 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();
    
            ...
        }
    });