Measure view in fragment

slezadav picture slezadav · Sep 10, 2012 · Viewed 9.6k times · Source

I need to know ImageView width and height. Is there a way to measure it in fragment ? In standard Activity I use this :

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    image.getWidth();
    image.getHeight();
}

But where can I use image.getWidth(); and image.getHeight(); in fragment ?

Answer

DeeV picture DeeV · Sep 10, 2012

Use the GlobalLayoutListener. You assign the listener to your ImageView in onCreateView() just like you do in that answer in the link. It also is more reliable than onWindowFocusChanged() for the main Activity so I recommend switching strategies.

EDIT

Example:

final View testView = findViewById(R.id.view_id);
ViewTreeObserver vto = testView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    Log.d("TEST", "Height = " + testView.getHeight() + " Width = " + testView.getWidth());
    ViewTreeObserver obs = testView.getViewTreeObserver();
    obs.removeGlobalOnLayoutListener(this);
  }
});