美文网首页
Android NestedScrollView嵌套WebVie

Android NestedScrollView嵌套WebVie

作者: 孟校长 | 来源:发表于2023-03-14 14:31 被阅读0次

不说废话

最近开发中遇到一个比较奇怪的问题,在NestedScrollView中嵌套了WebView,但是WebView加载完成后,底部会出现大量空白,甚至超过屏幕高度。
布局文件大致是这样的:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <com.example.WebEntranceView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="12dp"
            android:layout_marginTop="12dp" />

        <WebView
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</androidx.core.widget.NestedScrollView>

看到网上说了好多方案,比如:
(1) 对外层的NestedScrollView设置android:fillViewport="true";
(2) 给WebView设置固定的高度;
(3) 通过js回调让前端将h5内容的高度传递给端上进行设置;
等等等方案。。。。。。
对于以上方案,我只能说方案1、2干脆就是扯淡,真的不接受反驳;方案3我没有试,主要因为成本有些高,毕竟只在Android一端出现的问题,人家前端也不见得一定愿意帮你弄。

解决方案

经过本人反复的研究,反复的尝试,最终在孙子兵法中找到了以下方案,目前发现确实解决了问题,并且多机型上都OK的:
在代码中对WebView设置加载完成回调,并在回调用对WebView进行相关设置,如下:

webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // bugFix 解决NestedScrollView嵌套WebView底部留白问题
                webView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
            }
        });

说在最后

如果此方案不灵,还望轻喷,我这边这么操作确实是管用的。另外,要记得一定要在加载完成后设置WebView的LayoutParams的height为WRAP_CONTENT(直接在布局中设置我发现不管用,这也是很玄学的地方)。

相关文章

网友评论

      本文标题:Android NestedScrollView嵌套WebVie

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