Skip to content

Instantly share code, notes, and snippets.

@patrickhammond
Created February 3, 2014 20:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save patrickhammond/8791319 to your computer and use it in GitHub Desktop.
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.
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
}
});
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