14

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 ?

slezadav
  • 6,104
  • 7
  • 40
  • 61

1 Answers1

29

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);
  }
});
Community
  • 1
  • 1
DeeV
  • 35,865
  • 9
  • 108
  • 95
  • 1
    To add to this answer... I tried to use this snippet to get the width and height for an ImageView in a fragment displayed by ActionBar Tab listener. (Using support.V4 api, targeting API14+) I had to place the snippet into the 'onViewCreated' method(?) to get results. In fact in 'onCreateView' the testView object was null, View not found, and this caused exception. – user2238983 Apr 03 '13 at 05:43
  • You should be able to apply it to the view you return in onCreateView though. The reason it would return null would be because `profileContainer` doesn't exist yet. – DeeV Apr 03 '13 at 09:57
  • 1
    What are profilePadding and profileContainer types? – Stealth Rabbi Jul 08 '14 at 14:22
  • @StealthRabbi They are both `View` objects or anything that descends from `View`. – DeeV Jul 08 '14 at 18:41
  • @DeeV Not a very good explanation for the profilePadding and profileContainer types. – basickarl May 10 '15 at 22:49
  • @KarlMorrison They're `View`s. The method `View#addOnGlobalLayoutListener` is a method in `View`. `profilePadding` I think was a copy-paste error, so I edited to correct references. – DeeV May 11 '15 at 20:38
  • You need to check that testView.getHeight() or testView.getWidth() is not equal to 0 before stop observing with removeOnGlobalLayoutListener due you can get onGlobalLayout call some times with (0,0) – avgx Nov 09 '15 at 15:05