Listening to scroll events on Android views

What is the problem?

While the need to listen to scroll events of arbitrary views in Android has always existed, no such mechanisms were provided by Google until Android API level 23. That is when View.OnScrollChangeListener made its appearance. Until then, some views (e.g ListView) had custom mechanisms to listen to scroll events, but there was no common way. We, at Bugsee, have faced this problem while working on automatic concealment of protected web page elements (see Bugsee Privacy). We had to know when elements change their position, and no such mechanism exists for WebView for earlier Android versions.

The first idea that may come to mind is to extend each class and override the onScrollChanged() method in the subclass. Extending each and every view class doesn’t seem like a very practical thing to do. On top of that, we had to listen to scroll events of an existing WebView instance, passed to Bugsee as a parameter. So that approach was definitely not an option for us.

Luckily, Android SDK provides a way to listen to all scroll type events in the view hierarchy using ViewTreeObserver.OnScrollChangedListener. The class exists since Android API level 3. The inconvenience of this method, however, comes from the fact that ViewTreeObserver might be shared between multiple views, thus further filtering must be done to determine the one that was actually affected. In this article, we will learn to work with ViewTreeObserver.OnScrollChangedListener to encapsulate the complexities while avoiding the common pitfalls.


Helper class interface

Let’s create helper class for these goals – ListenScrollChangesHelper. This class should have the following public methods.

For compatibility reasons, OnScrollChangeListenerCompat interface will have the signature of View.OnScrollChangeListener that we are trying to mimic. This will allow us to easily fall back to the native solution if we happen to run on Android API level 23 or later. The clients will register to listen to scroll events of a view by adding it via an addViewToListen() method, while removeViewToListen() will stop monitoring events for that specific view respectively. And call to clear() method stops scroll events listening for all views added before.

Helper class implementation

Now, when everything is clear with the interface of this helper, let’s take a look at its implementation.

We use WeakHashMap instead of HashMap to avoid potential memory leaks. View has back reference to its activity, thus using strong references might prevent the whole activity from being garbage collected.

In addViewToListen() method we check the device API level and if it is at least 23, use native View.OnScrollChangeListener, wrapping OnScrollChangeListenerCompat in simple adapter OnScrollChangeListenerAdapter. When possible, it is always preferred to use the native mechanism as it might be better optimized and thus decrease computational overhead.

On devices with lower API level, we add the listener to the ViewTreeObserver of the monitored view. Note, that we call removeOnScrollChangedListener() prior to calling addOnScrollListener(). It is a common practice when adding listeners which helps avoid adding the same listener twice. In our case its a real possibility, as two monitored views might share the same ViewTreeObserver.

Within the ViewTreeObserver.OnScrollChangedListener’s onScrollChanged() method we iterate over the monitored views, find the one that actually scrolled and notify only the listener of that particular view.

Since, ViewTreeObserver is not guaranteed to remain valid for the lifetime of a view, we check it and update if necessary in view’s OnLayoutChangeListener. One more thing to take into account is that ViewTreeObserver, which is not alive, will throw exception on call to any method except isAlive(). Methods safeAddOnScrollChangeListener() and safeRemoveOnScrollChangeListener() help to deal with this problem by first checking isAlive() method result.

In this tutorial we’ve created a generic mechanism for listening to scroll events from any view, that works on a wide variety of Android API levels.

Full source code, along with a sample project that demonstrates the functionality is hosted on github. Feel free to download and try it yourself.

The sample project contains one activity with WebView and Listen/Stop listening buttons which start and stop monitoring for WebView scroll events respectively.