4

I'm getting height and width of a view, inflated in the getView() method. It's a grid item.

Usually I use post() on the view to get the size, after it was 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 do I get the size?

User
  • 31,811
  • 40
  • 131
  • 232

3 Answers3

1

While using a viewTreeObserver definitely works, I have found that calling measurements requirements on inflated views can be done reliably using a runnable from the activity's view. i.e.

someActivityInstance.getWindow().getDecorView().post(new Runnable() {
    @override
    public void run() {
        // someMeasurements
    }
});
rperryng
  • 3,233
  • 3
  • 22
  • 35
0

The thing is that convertview most likely is not drawn on the phone screen yet, so you have to wait until it is ready.

You need to use a ViewTreeObserver, to know exactly when the view has been drawn.

Check this answer for more info: When Can I First Measure a View?

Community
  • 1
  • 1
Julian Suarez
  • 4,499
  • 4
  • 24
  • 40
0

You probably is calling this at onCreate or onStart or onResume, methods which runs before layout measure. But there is a lot of work arounds, this is one good option:

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

Where rootView may be any viewGroup in a higher level than the one you want the width. But be aware that this listner may run more than once.

Pozzo Apps
  • 1,859
  • 2
  • 22
  • 32