Android : WebView無網路時的圖片顯示解決方案
阿新 • • 發佈:2019-01-28
需求場景:必須在已經構建快取的基礎之上,否則資料都無法正常顯示,何談圖片呢?
接下來直接上程式碼嘍,小夥伴們如果有更好的解決方式可以隨時聯絡我哦!
<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的相關筆記,希望大家多多支援!