Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does removeOnGlobalLayoutListener throw a NoSuchMethodError?

Tags:

android

I have some code that compiles successfully using ViewTreeObserver#removeOnGlobalLayoutListener(...) and when it runs, this method throws NoSuchMethodError. Why?

like image 299
Andrew Wyld Avatar asked Mar 01 '13 16:03

Andrew Wyld


Video Answer


2 Answers

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); } 
like image 147
Andrew Wyld Avatar answered Oct 12 '22 17:10

Andrew Wyld


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.

like image 25
azertiti Avatar answered Oct 12 '22 18:10

azertiti