首页 > 代码库 > ScrollView的滑动监听(以HorizontalScrollView为例)

ScrollView的滑动监听(以HorizontalScrollView为例)

ScrollView不能像其他组件一样使用onScrollChanged()方法是因为它用protected封装了
protected void onScrollChanged(int x, int y, int oldx, int oldy);
想要实现监听需要简单自定义组件.

1:自定义组件

public class ObservableScrollView extends HorizontalScrollView {

    private ScrollViewListener scrollViewListener = null;

    public ObservableScrollView(Context context) {
        super(context);
    }

    public ObservableScrollView(Context context, AttributeSet attrs,
                                int defStyle) {
        super(context, attrs, defStyle);
    }

    public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }

}

接口:

public interface ScrollViewListener {
    void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy);
}

2:使用监听

 horizontalScrollView.setScrollViewListener(new ScrollViewListener() {//滑动监听,获取图片
                @Override
                public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                    int scrollX = scrollView.getScrollX();
                    int width = scrollView.getWidth();
                    int scrollViewMeasuredWidth = holder.imageSL.getChildAt(0).getMeasuredWidth();
                    if ((scrollX + width) == scrollViewMeasuredWidth) {
//                        System.out.println("滑动到了底部 scrollY=" + scrollX + "height=" + width + "scrollViewMeasuredHeight=" + scrollViewMeasuredWidth);
                    }
                }
            });


ScrollView的滑动监听(以HorizontalScrollView为例)