2

I have this code:

ViewThreeObserver observer = my_view.getViewTreeObserver();
observer.addOnScrollChangedListener(new OnScrollChangedListener() {

    @Override
public void onScrollChanged() {
        if(condition) {
        //do something
        }
    }
});

Now I would remove listener on observer if condition is verified. I've try with:

 observer.addOnScrollChangedListener(null);

But I get an error that claim "ViewThreeObserver is not alive". What does it mean, and how I could remove listener correctly?

Bishan
  • 15,211
  • 52
  • 164
  • 258
giozh
  • 9,868
  • 30
  • 102
  • 183

2 Answers2

3

observer is a long-lived reference which has no guarantee to be valid for the lifetime of the view. Instead you can just call getViewTreeObserver on your view again and remove the listener (use removeOnScrollChangedListener as Ahmad mentioned).

my_view.getViewTreeObserver().removeOnScrollChangedListener(this);

Although this is a short-lived call, there is a potential of it being not alive so you could check isAlive on it beforehand (never experienced this myself).

You can also use isAlive on observer if you wanted to (most likely will not be alive) and use that to remove the listener. If observer is not alive you will need to call getViewTreeObserver anyway.

Quote for getViewTreeObserver

Returns the ViewTreeObserver for this view's hierarchy. The view tree observer can be used to get notifications when global events, like layout, happen. The returned ViewTreeObserver observer is not guaranteed to remain valid for the lifetime of this View. If the caller of this method keeps a long-lived reference to ViewTreeObserver, it should always check for the return value of isAlive().

I've seen many different variations of this here are a few:

Community
  • 1
  • 1
singularhum
  • 5,072
  • 2
  • 24
  • 32
0

Use ViewTreeObserver#removeOnScrollChangedListener(...) instead of setting the listener to null.

I get an error that claim "ViewThreeObserver is not alive"

It's recommended that you check with ViewTreeObserver#isAlive() if the ViewTreeObserver is alive or not before removing the listener.

Ahmad
  • 69,608
  • 17
  • 111
  • 137