Custom ScrollView code instance in Android

  • 2020-06-15 10:13:37
  • OfStack

ScrollView in Android is very simple, there is no OnScrollListener like ListView1, but it doesn't matter, we can inherit from ScrollView to customize 1 OnScrollListener. Without further ado, just code:


public class ObservableScrollView extends ScrollView {     public ObservableScrollView(Context context) {
        super(context);
    }     public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }     public ObservableScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }     public interface OnScrollChangedListener {
        public void onScrollChanged(int x, int y, int oldX, int oldY);
    }     private OnScrollChangedListener onScrollChangedListener;     public void setOnScrollListener(OnScrollChangedListener onScrollChangedListener) {
        this.onScrollChangedListener = onScrollChangedListener;
    }     @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (onScrollChangedListener != null) {
            onScrollChangedListener.onScrollChanged(x, y, oldX, oldY);
        }
    }
}

The above code is very simple, and I believe you can understand it. When you use it, you only need to call setOnScrollListener method. There are four parameters in it > oldY slides down and vice versa. There are other interesting things you can do, like determine if ScrollView is sliding to a particular location and do some animation, and more creatively it's up to you to think for yourself.


Related articles: