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?
You cannot use the
width
/height
/getMeasuredWidth
/getMeasuredHeight
on aView
before the system renders it (typically fromonCreate
/onResume
).Simple solution for this is to post a
Runnable
to the layout. The runnable will be executed after theView
has been laid out.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.Indeed, it appears that if the layout is not shown on the screen the getWidth() method returns 0. What seems to work for me is calling the measure() method before calling the getMeasuredWidth() or getMesuredHeight(). For the measure method I used the Layout.WRAP_CONTENT arguments to get a measurement of what the layout contains.
Hope this helps, Mihai
This answer says:
Use the
ViewTreeObserver
on theView
to wait for the first layout. Only after the first layout willgetWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight()
work.Solution #1: To do it dynamically, you need a tag. A tag is basically a way for views to have memories. So save the convertView in another class (MyTag). So inside your java file:
Solution #2: Hard-code it. Pre-set the width. Inside your res/values/dimens.xml file, include
Then inside your res/layout/your_layout.xml file, include
Then inside your java file:
Use below code: