打开scrollView的源代码发现scrollView,并没有和其他控件类型的setxxListener的监听。但是可以发现一个回调方法
/** * This is called in response to an internal scroll in this view (i.e., the * view scrolled its own contents). This is typically as a result of * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been * called. * * @param l Current horizontal scroll origin. * @param t Current vertical scroll origin. * @param oldl Previous horizontal scroll origin. * @param oldt Previous vertical scroll origin. */ protected void onScrollChanged(int l, int t, int oldl, int oldt) { notifySubtreeAccessibilityStateChangedIfNeeded(); if (AccessibilityManager.getInstance(mContext).isEnabled()) { postSendViewScrolledAccessibilityEventCallback(); } mBackgroundSizeChanged = true; if (mForegroundInfo != null) { mForegroundInfo.mBoundsChanged = true; } final AttachInfo ai = mAttachInfo; if (ai != null) { ai.mViewScrollChanged = true; } if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); } }从注释可以发现,当scrollView滚动的时候,系统会回调该方法。
所以可以通过建立一个接口,将该方法暴露出去
自定义scrollView如下:
/** * 有时候我们需要监听ScroView的滑动情况,比如滑动了多少距离, * 是否滑到布局的顶部或者底部。 * 可惜的是SDK并没有相应的方法,不过倒是提供了一个 * 方法,显然这个方法是不能被外界调用的,因此就需要把它暴露出去,方便使用。解决方式就是写一个接口, */ public class CustomScrollView extends ScrollView{ private OnScrollChangeListener mOnScrollChangeListener; /** * 设置滚动接口 * @param */ public void setOnScrollChangeListener(OnScrollChangeListener onScrollChangeListener) { mOnScrollChangeListener = onScrollChangeListener; } public CustomScrollView(Context context) { super(context); } public CustomScrollView(Context context, AttributeSet attrs) { super(context, attrs); } /** * *定义一个滚动接口 * */ public interface OnScrollChangeListener{ void onScrollChanged(CustomScrollView scrollView,int l, int t, int oldl, int oldt); } /** * 当scrollView滑动时系统会调用该方法,并将该回调放过中的参数传递到自定义接口的回调方法中, * 达到scrollView滑动监听的效果 * * */ @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if(mOnScrollChangeListener!=null){ mOnScrollChangeListener.onScrollChanged(this,l,t,oldl,oldt); } } }测试代码:
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class Main2Activity extends AppCompatActivity implements CustomScrollView.OnScrollChangeListener{ private CustomScrollView mCustomScrollView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); mCustomScrollView= (CustomScrollView) findViewById(R.id.scrollView); mCustomScrollView.setOnScrollChangeListener(this); } @Override public void onScrollChanged(CustomScrollView scrollView, int l, int t, int oldl, int oldt) { //获取滚动的参数(todoyourthing) } }是不是和Button控件的监听类似了