OnGlobalLayoutListener: deprecation and compatibility

I’m using this in my project:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){
    if (Build.VERSION.SDK_INT < 16) {
        v.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
    } else {
        v.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
    }
}

looks similar to yours.
Tested on different devices (4.2.2 & 2.3.3) and it run perfectly.
seems like it’s the only way….If you find anything else I would like to know it.
good luck

2020 EDIT
This approach is very very obsolete. I hope you moved your code to Kotlin.
Now we can use doOnPreDraw function when using ktx library.
https://developer.android.com/reference/kotlin/androidx/core/view/package-summary#(android.view.View).doOnPreDraw(kotlin.Function1)

Leave a Comment