需求场景:必须在已经构建缓存的基础之上,否则数据都无法正常显示,何谈图片呢?
接下来直接上代码喽,小伙伴们如果有更好的解决方式可以随时联系我哦!
<WebView
android:id="@+id/content"
android:layout_width="@dimen/dp_328"
android:layout_height="wrap_content"
android:layout_below="@id/instruction"
android:layout_centerHorizontal="true"
android:layout_marginTop="@dimen/dp_30">
</WebView>
对webView进行配置:
private fun webSetting() {
var ws = content.settings
ws.javaScriptEnabled = true //与Javascript交互
//Todo
ws.setAppCacheEnabled(true)
ws.databaseEnabled = true
ws.domStorageEnabled = true
//Todo
ws.setRenderPriority(WebSettings.RenderPriority.HIGH)////设置渲染的优先级
ws.defaultFontSize = 17 //设置默认字体大小,默认16,可取值1到72
ws.defaultTextEncodingName = "UTF-8"
content.isVerticalScrollBarEnabled = false
ws.cacheMode = WebSettings.LOAD_NO_CACHE//设置缓存模式</span>
在无网络的情况下:
if (!NetworkUtils.isConnected) {
aboutImageSetting()//断网操作
}
content.loadDataWithBaseURL(null, HtmlFormat.getNewContent(t?.content!!), "text/html", "utf-8", null)//加载详情
private fun aboutImageSetting() {
content.webViewClient = object : WebViewClient() {
// API 21 以上用shouldInterceptRequest(WebView view, WebResourceRequest request)
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse {
val toString = request?.url.toString()
// 步骤1:判断拦截资源的条件,即判断url里的图片资源
if (toString.contains(".jpg")) {
// 步骤2:创建一个输入流
var stream: InputStream? = null
try {
stream = assets.open("none_picture.png")
// 步骤3:获得需要替换的资源(存放在assets文件夹里)
} catch (e: IOException) {
e.printStackTrace()
}
// 步骤4:替换资源
var res = WebResourceResponse("image/jpeg",
"utf-8", stream)
// 参数1:http请求里该图片的Content-Type
// 参数2:编码类型
// 参数3:存放着替换资源的输入流(上面创建的那个)
return res
}
return super.shouldInterceptRequest(view, request)
}
//API21以下用shouldInterceptRequest(WebView view, String url)
override fun shouldInterceptRequest(view: WebView?, url: String?): WebResourceResponse {
if (url?.contains(".jpg")!!) {
var input: InputStream? = null
try {
input = applicationContext.assets.open("none_picture.png")
} catch (e: IOException) {
e.printStackTrace()
}
var res = WebResourceResponse("image/jpeg",
"utf-8", input)
return res
}
return super.shouldInterceptRequest(view, url)
}
}
最后千万不要忘记添加权限:
<uses-permission android:name="android.permission.INTERNET"/>
上述代码是用Kotlin写的,后续会推出Kotlin的相关笔记,希望大家多多支持!