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 EDITThis 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)
I think the correct way is using Build.VERSION.SDK_INT
and Build.VERSION_CODES
:
public static void removeOnGlobalLayoutListener(View v, ViewTreeObserver.OnGlobalLayoutListener listener){ if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { v.getViewTreeObserver().removeGlobalOnLayoutListener(listener); } else { v.getViewTreeObserver().removeOnGlobalLayoutListener(listener); }}
mView.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } else { //noinspection deprecation mView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } // // mycode // } });