【问题标题】:Webview not properly sized Jetpack compose (Autosizing Webview Composable)Webview 大小不正确 Jetpack compose (Autosizing Webview Composable)
【发布时间】:2023-01-18 16:45:56
【问题描述】:

我需要使用 WebView 代替 Text composable(显示复杂的文本和数学)。 WebView 的大小取决于内容(文本)的数量。但目前它仅在应用固定大小修改器时才有效。没有固定尺寸; WebView 在加载时断断续续,很多时候它甚至不会显示。

我正在使用 loadWithBaseUrl() 方法加载内容。 我尝试使用 Accompanist 库中的 WebView composable;还尝试了我的自定义实现;但它仍然无法正常工作。

// implementation 'com.google.accompanist:accompanist-webview:0.24.3-alpha'

    LazyColumn(){
        item {
            val webViewState = rememberWebViewStateWithHTMLData(data = FakeData.HTML_DOC)
            Surface(
                modifier = Modifier.padding(8.dp, 8.dp).height(IntrinsicSize.Min)
            ) {
                WebView(
                    state = webViewState,
                    modifier = Modifier
//                        .size(400.dp, 200.dp)  // When fixed size applied problem disappears
                )
            }
        }

    }

【问题讨论】:

  • 当我尝试将 WebView 放入包含其他一些可组合项的列中时,我遇到了类似的问题。我通过使用 Modifier.height(IntrinsicSize.Max) 在这方面取得了一些进展,但它仍然不稳定。你在 Accompanist GitHub 上提交了一个问题吗?
  • 你好@Paul T。我刚刚提交了这个问题。随时提出改进建议。这是链接:github.com/google/accompanist/issues/1224

标签: android webview android-webview android-jetpack-compose jetpack-compose-accompanist


【解决方案1】:

使用自定义AccompanistWebViewClient,覆盖onPageFinished,可以通过evaluateJavascript获取网页高度。

val jsWebHeight = "(function() {
" +
                        "	var body = document.body,
" +
                        "	html = document.documentElement;
" +
                        "	var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
" +
                        "	var width = html.scrollWidth;
" +
                        "	if (width > 0) return height;
" +
                        "	else return 0;
" +
                        "})();"
override fun onPageFinished(view: WebView?, url: String?) {
     super.onPageFinished(view, url)

     view?.let{ webView ->
          val width = webView.width
          if (width > 0) {
               webView.evaluateJavascript(jsWebHeight) { result ->
                    result?.toIntOrNull()?.let { height ->
                         if (height > 0) {
                              // set webView height here, height is dp unit
                         }
                    }
               }
          }
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2022-01-07
    • 2022-09-25
    • 2023-01-05
    • 2022-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多