【问题标题】:Android WebView partial HTML rendering problemAndroid WebView部分HTML渲染问题
【发布时间】:2021-01-06 10:55:15
【问题描述】:

我的 HTML 很简单,应该这样渲染

但是 android webview 会丢失一些内容并像这样渲染它

导致问题的行是这个 <a name="_ftnref1" href="#_ftn1">[1]</a>

如何调整 HTML 或 webview 以正确呈现所有内容?

MainActivity.kt

import android.os.Bundle
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    val html = """
        <!DOCTYPE html>
        <html>
            <head></head>
            <body>
                <ul>
                    <li>content above link</li>
                    <li>The link is on this line 
                        <a name="_ftnref1" href="#_ftn1">[1]</a>
                    </li>
                    <li>content below link</li>
                </ul>
                <p>
                    <a name="_ftn1" href="#_ftnref1">[1]</a> Link landing
                </p>
            </body>
        </html>
    """.trimIndent()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<WebView>(R.id.web_view).loadData(html, "text/html", "UTF-8")
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

【问题讨论】:

    标签: android html webview


    【解决方案1】:

    尝试在这个你的activity_main.xml中

    <supports-screens android:smallScreens="true"
          android:normalScreens="true" 
          android:largeScreens="true"
      android:anyDensity="true" />
    

    【讨论】:

      【解决方案2】:

      奇怪的是,我通过从文件而不是从内存中加载 html 内容解决了我的问题。为什么它以这种方式工作,而以另一种方式工作我不知道。

      // HTML will be rendered correctly
      val file = File(filesDir, "temp.html")
      file.writeText(html, Charset.forName("UTF-8"))
      
      val webView = findViewById<WebView>(R.id.web_view)
      webView.settings.allowFileAccess = true
      webView.loadUrl("file://" + file.absolutePath)
      
      // HTML will be rendered incorrectly
      // webView.loadData(html, "text/html", "UTF-8")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-06
        • 2019-01-31
        相关资源
        最近更新 更多