Instantly share code, notes, and snippets.

Embed
What would you like to do?
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