android SwipeRefreshLayout嵌套Webview滑动冲突问题解决

1,052 阅读1分钟

在网页中实现下拉刷新功能,这里遇到一个坑,加载网页的时候webview向上滑动不了了,看了一下网上的资料尝试过后都没有用,在这里做一下记录,由于两个控件都有滑动的事件,在向下滑动的时候滑动事件被SwipeRefreshLayout控件优先覆盖了,这里的话可以监听webview的滑动事件对SwipeRefreshLayout是否允许下拉刷新进行控制。

1.layout布局

    <android.support.v4.widget.SwipeRefreshLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.xxxxxx.view.MyWebView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

2.自定义Webview得到onScrollChanged方法的监听事件

public class MyWebView extends WebView {

    public MyWebView(Context context) {
        super(context);
    }

    public MyWebView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
    }

    public MyWebView(Context context, AttributeSet attributeSet, int i) {
        super(context, attributeSet, i);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (mScrollListener != null) {
            mScrollListener.onScrollChanged(t);
        }
    }

    public interface IScrollListener {
        void onScrollChanged(int scrollY);
    }

    private IScrollListener mScrollListener;

    public void setOnScrollListener(IScrollListener listener) {
        mScrollListener = listener;
    }
}

3.初始化控件调用setOnScrollListener接口,控制可下拉刷新时机

   SwipeRefreshLayout mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
      mMyWebview.setOnScrollListener(new ExplorerWebView.IScrollListener() {
                @Override
                public void onScrollChanged(int scrollY) {
                    if (scrollY == 0) {
                    //开启下拉刷新
                        mSwipeRefresh.setEnabled(true);
                    } else {
                    //关闭下拉刷新
                        mSwipeRefresh.setEnabled(false);
                    }
                }
            });