Skip to content

Instantly share code, notes, and snippets.

@dominicthomas
Created November 1, 2013 14:41
Show Gist options
  • Save dominicthomas/7266405 to your computer and use it in GitHub Desktop.
Save dominicthomas/7266405 to your computer and use it in GitHub Desktop.
How to add and remove a viewtreeobserver to an android view. This lets you call stuff when the view is finished rendering.
final ViewTreeObserver vto = myview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressLint("NewApi")
@Override
public void onGlobalLayout() {
// do stuff
// remove this layout listener - as it will run every time the view updates
if (myview.getViewTreeObserver().isAlive()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
myview.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
myview.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment