Android SwipeRefreshLayout巢狀Webview滑動衝突問題解決
最近有一個需求,需要在網頁中實現下拉重新整理功能,這裡遇到一個坑,載入網頁的時候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); } } });
OK,我的衝突問題解決了,不過開發中同一個需求根據專案情況實現的方式也會不一樣,解決方式也會不同,這裡提供的是解決方法之一。