对于所有对 webview 和 nestedscrollview 有相同问题的人。我找到了解决方案。我在 nestedscrollview 上设置了一个 setOnScrollChangeListener 并将当前滚动位置作为 javascript 事件触发。
我的片段布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/swRefresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.NestedScrollView
android:id="@+id/nsvScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<WebView
android:id="@+id/wvTest"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.NestedScrollView>
还有我的片段:
public class TestFragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SwipeRefreshLayout view = (SwipeRefreshLayout)inflater.inflate(R.layout.fragment_test, container, false);
NestedScrollView nsvScrollView = (NestedScrollView)view.findViewById(R.id.nsvScrollView);
final WebView wvTest = (WebView)view.findViewById(R.id.wvTest);
nsvScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
wvTest.loadUrl("javascript:scrollEvent.scrollY = " + scrollY + "; window.dispatchEvent(scrollEvent);");
}
});
wvTest.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
wvTest.loadUrl("javascript:var scrollEvent = document.createEvent(\"Event\"); scrollEvent.initEvent(\"scroll\", true, true);");
}
});
wvTest.getSettings().setJavaScriptEnabled(true);
WebView.setWebContentsDebuggingEnabled(true);
wvTest.loadUrl("http://yoursite.com");
return view;
}
}
在网站上,您可以添加默认滚动侦听器:
<script>
window.addEventListener('scroll', function (e) {
console.log("Scroll: " + e.scrollY);
}, false);
</script>