If I call getMeasuredWidth() or getWidth() for layout in onResume they return 0
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(); ... }});
This answer says:
Use the ViewTreeObserver
on the View
to wait for the first layout. Only after the first layout will getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight()
work.
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();if (viewTreeObserver.isAlive()) { viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); viewWidth = mediaGallery.getWidth(); viewHeight = mediaGallery.getHeight(); } });}
you can override onLayout() in your view; this is used by android to position each of the children the view has, so you could do the stuff you want to do there after the super(..)
call.