SoFunction
Updated on 2025-04-10

Android development ScrollView Sliding Monitoring

We need to monitor the sliding situation of the ScroView, such as how far it has been sliding, and whether it has been sliding to the top or bottom of the layout. Unfortunately, the SDK does not have a corresponding method, but it provides a

protected void onScrollChanged(int l, int t, int oldl, int oldt)

Obviously, this method cannot be called by the outside world, so it needs to be exposed. The solution is to write an interface.

/**
 * Created by Liu Nan on 2016/8/21 0021.17:24
 */
public interface ScrollViewListener {
void onScrollChanged(ObservableScrollView observableScrollView,int x,int y ,int oldx, int oldy);
}

Then rewrite the ScrollView class and provide it with the callback interface written above.

package ;
import ;
import ;
import ;
/**
 * Created by Liu Nan on 2016/8/21 0021.17:23
 */
public class ObservableScrollView extends ScrollView {
private ScrollViewListener mScrollViewListener=null;
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
mScrollViewListener = scrollViewListener;
}
public ObservableScrollView(Context context) {
super(context);
}
public ObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onScrollChanged(int x, int y, int oldx, int oldy) {
(x, y, oldx, oldy);
if (mScrollViewListener != null) {
(this, x, y, oldx, oldy);
}
}
} 

When laying out, use the rewritten ScrollView