直接上代碼:
自定義一個Webview
public class TermsWebView extends WebView {
ScrollInterface mScrollInterface;
// 構(gòu)造函數(shù)
public TermsWebView(Context context) {
super(context);
}
// 構(gòu)造函數(shù)
public TermsWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
// 構(gòu)造函數(shù)
public TermsWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
// 復(fù)寫 onScrollChanged 方法,用來判斷觸發(fā)判斷的時機
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mScrollInterface != null){
mScrollInterface.onSChanged(l, t, oldl, oldt);
}
}
// 定義接口
public void setOnCustomScrollChangeListener(ScrollInterface mInterface) {
mScrollInterface = mInterface;
}
public interface ScrollInterface {
void onSChanged(int scrollX, int scrollY, int oldScrollX, int oldScrollY);
}
}
使用的地方:
mWebView.setOnCustomScrollChangeListener((scrollX, scrollY, oldScrollX, oldScrollY) -> {
// isLoadError 判斷webview是否加載成功
if (!mWebView.canScrollVertically(1) && !isLoadError) {
mAgreeText.setEnabled(true); // button 可點擊
}
});
這個地方使用自定義的接口方式是因為:

setOnScrollChangeListener.png
其中用來判斷能否滑動的關(guān)鍵方法是 :canScrollVertically()。這個方法是View的方法,直接上源碼:
/**
* Check if this view can be scrolled horizontally in a certain direction.
*
* @param direction Negative to check scrolling left, positive to check scrolling right.
* @return true if this view can be scrolled in the specified direction, false otherwise.
*/
public boolean canScrollHorizontally(int direction) {
final int offset = computeHorizontalScrollOffset();
final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}
/**
* Check if this view can be scrolled vertically in a certain direction.
*
* @param direction Negative to check scrolling up, positive to check scrolling down.
* @return true if this view can be scrolled in the specified direction, false otherwise.
*/
public boolean canScrollVertically(int direction) {
final int offset = computeVerticalScrollOffset();
final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
if (range == 0) return false;
if (direction < 0) {
return offset > 0;
} else {
return offset < range - 1;
}
}