Why does removeOnGlobalLayoutListener throw a NoSuchMethodError?

There are two methods in ViewTreeObserver with almost the same name.

removeOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener victim)

(on then global) is a method that was added in API 16. It replaces

removeGlobalOnLayoutListener(ViewTreeObserver.OnGlobalLayoutListener victim)

(global then on) which has existed since API 1, but which is now deprecated.

Both methods can appear present at compile-time (if you’re building against Jellybean or higher) but the newer one will fail on pre-Jellybean devices.

This code thwarts the error:

try {
    thing.removeOnGlobalLayoutListener(victim);
} catch (NoSuchMethodError x) {
    thing.removeGlobalOnLayoutListener(victim);
}

So does this code:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    thing.removeGlobalOnLayoutListener(victim);
} else {
    thing.removeOnGlobalLayoutListener(victim);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)