Created
February 3, 2014 20:03
-
-
Save patrickhammond/8791319 to your computer and use it in GitHub Desktop.
Safe usage of a ViewTreeObserver to get view measurements. This ensures that the layout listener isn't leaked and the right API calls are made.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final View view = findViewById(R.id.my_view); | |
notifyWhenMeasured(view, new OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
int viewWidth = view.getMeasuredWidth(); | |
int viewHeight = view.getMeasuredHeight(); | |
// Now you can do the interesting stuff | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void notifyWhenMeasured(final View view, final ViewTreeObserver.OnGlobalLayoutListener listener) { | |
ViewTreeObserver vto = view.getViewTreeObserver(); | |
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
listener.onGlobalLayout(); | |
// Need to get a fresh ViewTreeObserver | |
ViewTreeObserver freshVto = view.getViewTreeObserver(); | |
if (Build.VERSION.SDK_INT < 16) { | |
// Deprecated because it was inconsistently named | |
freshVto.removeGlobalOnLayoutListener(this); | |
} else { | |
freshVto.removeOnGlobalLayoutListener(this); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment