1 package com.ft.mysinaweibo; 2 3 import java.lang.reflect.Field; 4 import java.lang.reflect.Method; 5 6 import android.content.Context; 7 import android.os.Handler; 8 import android.util.AttributeSet; 9 import android.util.Log; 10 import android.view.GestureDetector; 11 import android.view.GestureDetector.SimpleOnGestureListener; 12 import android.view.MotionEvent; 13 import android.view.View; 14 import android.webkit.WebView; 15 import android.widget.AbsListView.OnScrollListener; 16 import android.widget.ScrollView; 17 import android.widget.Scroller; 18 19 /** 20 * 自定义ScrollView,解决: 1. ScrollView嵌套ViewPager,导致ViewPager不能滑动的问题 2. 21 * ScrollView源码并没有实现滚动监听,所以我们必须自行实现对ScrollView的监听, 22 * 我们很自然的想到在onTouchEvent()方法中实现对滚动Y轴进行监听 ScrollView的滚动Y值进行监听 23 * 24 */ 25 public class CustomScrollView extends ScrollView { 26 private GestureDetector mGestureDetector; 27 private int Scroll_height = 0; 28 private int view_height = 0; 29 protected Field scrollView_mScroller; 30 private static final String TAG = "CustomScrollView"; 31 32 private OnScrollListener onScrollListener; 33 private int lastScrollY;// ScrollView在Y方向滑动的最后距离 34 35 public CustomScrollView(Context context, AttributeSet attrs) { 36 super(context, attrs); 37 // mGestureDetector = new GestureDetector(context, new 38 // YScrollDetector()); 39 setFadingEdgeLength(0); 40 } 41 42 // --------------------------------------------------------------------------// 43 /** 44 * 设置滚动接口 45 * 46 * @param onScrollListener 47 */ 48 public void setOnScrollListener(OnScrollListener onScrollListener) { 49 this.onScrollListener = onScrollListener; 50 } 51 52 /** 53 * 用于用户手指离开MyScrollView的时候获取MyScrollView滚动的Y距离,然后回调给onScroll方法中 54 */ 55 private Handler handler = new Handler() { 56 57 public void handleMessage(android.os.Message msg) { 58 int scrollY = CustomScrollView.this.getScrollY(); 59 60 // 此时的距离和记录下的距离不相等,在隔5毫秒给handler发送消息 61 if (lastScrollY != scrollY) { 62 lastScrollY = scrollY; 63 handler.sendMessageDelayed(handler.obtainMessage(), 5); 64 } 65 if (onScrollListener != null) { 66 onScrollListener.onScroll(scrollY); 67 } 68 69 }; 70 71 }; 72 73 /** 74 * 滚动的回调接口 75 */ 76 public interface OnScrollListener { 77 /** 78 * 回调方法, 返回MyScrollView滑动的Y方向距离 79 */ 80 public void onScroll(int scrollY); 81 } 82 83 84 85 @Override 86 public boolean onTouchEvent(MotionEvent ev) { 87 int scrollY = getScrollY(); 88 89 // 此时的距离和记录下的距离不相等,在隔5毫秒给handler发送消息 90 if (lastScrollY != scrollY) { 91 lastScrollY = scrollY; 92 handler.sendMessageDelayed(handler.obtainMessage(), 5); 93 } 94 if (onScrollListener != null) { 95 onScrollListener.onScroll(scrollY); 96 } 97 return super.onTouchEvent(ev); 98 } 99 100 } 101 102
时间: 2024-11-05 15:51:03