在 Android Kotlin 中,使用原始 WebView 加载字符串 HTML 并处理图片加载失败的方法是通过重写 WebView 的 shouldInterceptRequest 方法。shouldInterceptRequest 方法允许我们拦截 WebView 中的网络请求,这样我们可以自定义处理请求。\n\n下面是一个示例代码:\n\nkotlin\nwebView.settings.javaScriptEnabled = true\n\nwebView.webViewClient = object : WebViewClient() {\n override fun shouldInterceptRequest(\n view: WebView?,\n request: WebResourceRequest?\n ): WebResourceResponse? {\n val url = request?.url.toString()\n\n if (url.endsWith(".jpg") || url.endsWith(".png") || url.endsWith(".gif")) {\n // 处理图片请求\n try {\n val inputStream = FileInputStream("/path/to/local/image.jpg") // 替换成你的本地图片路径\n val contentType = "image/jpeg" // 替换成你的图片类型\n return WebResourceResponse(contentType, "UTF-8", inputStream)\n } catch (e: FileNotFoundException) {\n e.printStackTrace()\n } \n }\n\n return super.shouldInterceptRequest(view, request)\n }\n}\n\nval html = "<html><body><img src='http://example.com/image.jpg' /></body></html>"\nwebView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null)\n\n\n在上面的示例中,我们重写了 shouldInterceptRequest 方法,并判断请求的 URL 是否以 .jpg、.png 或 .gif 结尾。如果是图片请求,我们可以将本地图片通过 FileInputStream 加载,并返回 WebResourceResponse 对象。\n\n请注意,上面的示例中使用的是本地图片作为替代,你需要将 /path/to/local/image.jpg 替换为你的本地图片路径,并将 image/jpeg 替换为你的图片类型。\n\n这样,当 WebView 加载字符串 HTML 时,如果遇到图片加载失败,将会使用本地图片替代。

Android Kotlin WebView 加载字符串 HTML 图片加载失败解决方案

原文地址: https://www.cveoy.top/t/topic/qpEf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录