WebView 滑动监听

目前功能需要监听webview的滑动状态,但是webview本身没有滑动监听

谷歌在API23版本 为View添加了一个方法

/** * Register a callback to be invoked when the scroll X or Y positions of
 * this view change. 
* 

* Note: Some views handle scrolling independently from View and may * have their own separate listeners for scroll-type events. For example, * {@link android.widget.ListView ListView} allows clients to register an * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} * to listen for changes in list scroll position. * * @param l The listener to notify when the scroll X or Y position changes. * @see android.view.View#getScrollX() * @see android.view.View#getScrollY() */ public void setOnScrollChangeListener(OnScrollChangeListener l) { getListenerInfo().mOnScrollChangeListener = l; }复制代码

通过这个方法获取webview的滑动状态,但是 之前的版本怎么办呢?

自定义一个webview如下

public class ScrollWebView extends WebView {    
private OnScrollChangedCallback mOnScrollChangedCallback;    
public ScrollWebView(final Context context) {
        super(context);    
}    
public ScrollWebView(final Context context, final AttributeSet attrs) {        
super(context, attrs);    
}    
public ScrollWebView(final Context context, final AttributeSet attrs,                         
final int defStyle) {        super(context, attrs, defStyle);    
}    
@Override    
protected void onScrollChanged(final int l, final int t, final int oldl,                                   
final int oldt) {        super.onScrollChanged(l, t, oldl, oldt);        
if (mOnScrollChangedCallback != null) {            
mOnScrollChangedCallback.onScroll(l - oldl, t - oldt);        
}    
}    
public OnScrollChangedCallback getOnScrollChangedCallback() {
        return mOnScrollChangedCallback;    
}    
public void setOnScrollChangedCallback(            
final OnScrollChangedCallback onScrollChangedCallback) {        
mOnScrollChangedCallback = onScrollChangedCallback;    
}    
/**     
* Impliment in the activity/fragment/view that you want to listen to the webview     
*/    
public  interface OnScrollChangedCallback {         
void onScroll(int dx, int dy);    
}
}复制代码


在使用的地方 实现onScroll方法

 public void onScroll(int dx, int dy) {    
        //todo 你的骚操作
}复制代码


你可能感兴趣的:(WebView 滑动监听)