Why is the width and height of the view 0 in post () runnable?

I get the height and width of the view inflated by the getView () method. This is a grid item.

I usually use post () in a view to get the size after it has been attached to the layout. But it returns 0.

final View convertViewFinal = convertView; convertView.post(new Runnable() { @Override public void run() { doSomethingWithConvertView(convertViewFinal); } }); 

...

 doSomethingWithConvertView(View v) {v.getWidth(); /*returns 0*/}; 

How to get the size?

+4
source share
3 answers

When using the viewTreeObserver function, I found that call measurement requirements for inflated views can be reliably met using runnable from an activity view. i.e.

 someActivityInstance.getWindow().getDecorView().post(new Runnable() { @override public void run() { // someMeasurements } }); 
+1
source

The fact is that convertview, most likely, is not yet displayed on the phone screen, so you need to wait until it is ready.

You need to use ViewTreeObserver to know exactly when the view was displayed.

Check this answer for more information: When can I measure the view first?

0
source

You probably call this onCreate or onStart or onResume, methods that are executed before the layout is measured. But there is a lot of work around, this is one good option:

 ViewTreeObserver vto = rootView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { public void onGlobalLayout() { v.getWidth();//already measured... } }); 

If rootView can be any viewGroup at a higher level than the one you want to use for width. But keep in mind that this list may work several times.

0
source

All Articles