I have some code that compiles successfully using ViewTreeObserver#removeOnGlobalLayoutListener(...)
and when it runs, this method throws NoSuchMethodError
. Why?
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); }
I assume you are talking about removeOnGlobalLayoutListener from ViewTreeObserver class. This method was added in API level 16. My best guess is that you try to use it on a device running an old version of Android that's why it can't be found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With