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: