1

我有一个自定义错误页面要显示在 Web 视图中,该页面存储在默认资产文件夹中C:\Users\User\StudioProjects\Appname\app\src\main\assets\error.html

在我这样加载页面的onReceivedError方法中WebViewClientview.loadUrl("file:///android_asset/error.html");

当我编码和测试它时它工作正常,但奇怪的是,我再次测试它,Webview 显示此错误
The webpage at file:///android_asset/error.html could not be loaded because: net::ERR_FILE_NOT_FOUND

我尝试了https://stackoverflow.com/a/37994555/4722232的解决方案,它适用于 html,但我在其中有一个徽标并且遇到了同样的问题,并且在我得到的日志中

"Not allowed to load local resource: file:///android_asset/logo.png", source: about:blank (0)

任何帮助将不胜感激

4

1 回答 1

1
  1. 从资产中读取文件并加载到 WebView
val htmlFile = "file:///android_asset/file_name.extension" //e.g. index.html
webView.loadUrl(htmlFile)

资产文件夹必须在里面main

  1. 从asset文件夹中获取文件内容,然后加载到WebView
val inputStream = assets.open("file_name.extension")
val buffer = BufferedInputStream(inputStream)
val bytes = buffer.readBytes()
val content = String(bytes)
buffer.close()
webView.loadData(String(content), "text/html", "utf-8")
  1. raw从文件夹中读取文件

res-> raw->file_name.extension

val inputStream = resources.openRawResource(R.raw.index)
val buffer = BufferedInputStream(inputStream)
val bytes = buffer.readBytes()
val content = String(bytes)
buffer.close()
webView.loadData(String(content), "text/html", "utf-8")

您可以使用 Kotlin Extensions 来简化此过程

assets.open("file_name.extension").bufferedReader().use { br ->
    webView.loadData(br.readText(), "text/html", "utf-8")
}

确保您的 file_name.extension 是小写的,并且仅包含 _ 如果它们在其中一个resassets文件夹中。

于 2020-06-25T16:59:03.443 回答