美文网首页
ScrollView的滑动监听(以HorizontalScro

ScrollView的滑动监听(以HorizontalScro

作者: AiPuff | 来源:发表于2016-10-22 15:54 被阅读2369次

    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的滑动监听(以HorizontalScro

          本文链接:https://www.haomeiwen.com/subject/snlhuttx.html