Skip to content

Instantly share code, notes, and snippets.

@dominicthomas
Created June 23, 2016 15:10
Show Gist options
  • Save dominicthomas/2859579cc1d8ef9091106574fbe93c56 to your computer and use it in GitHub Desktop.
Save dominicthomas/2859579cc1d8ef9091106574fbe93c56 to your computer and use it in GitHub Desktop.
A useful abstract class that wraps in global layout listener functionality to support older android versions.
public abstract class CompatGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
private final View view;
public CompatGlobalLayoutListener(@NonNull final View view) {
this.view = view;
}
protected abstract void onGlobalLayoutReady();
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
removeGlobalLayoutListenerPreJB();
} else {
removeGlobalLayoutListenerJB();
}
onGlobalLayoutReady();
}
@SuppressWarnings("deprecation")
private void removeGlobalLayoutListenerPreJB() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void removeGlobalLayoutListenerJB() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
public View getView() {
return view;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment