美文网首页
Android判断WebView是否滑动到顶部和底部

Android判断WebView是否滑动到顶部和底部

作者: FreedApe | 来源:发表于2019-08-23 08:59 被阅读0次

直接上代码:

自定义一个Webview

public class TermsWebView extends WebView {

    ScrollInterface mScrollInterface;
// 构造函数
    public TermsWebView(Context context) {
        super(context);
    }
// 构造函数
    public TermsWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
// 构造函数
    public TermsWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
// 复写 onScrollChanged 方法,用来判断触发判断的时机
    @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

其中用来判断能否滑动的关键方法是 :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;
        }
    }

相关文章

网友评论

      本文标题:Android判断WebView是否滑动到顶部和底部

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