目标
替换掉webView默认的报错页面。效果图如下:
主要代码
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initListeners()
initViews()
}
private fun initListeners() {
retryIv.setOnClickListener {
webView.reload()
webView.visibility = View.INVISIBLE
showErrorView(false)
}
}
private fun initViews() {
webView.loadUrl("https://www.baidu.com/")
webView.settings.javaScriptEnabled = true//设置webView属性,能够执行Javascript脚本
val webSettings = webView.settings
webSettings.javaScriptEnabled = true //允许加载javascript
webSettings.setSupportZoom(true) //允许缩放
webSettings.builtInZoomControls = true //原网页基础上缩放
webSettings.useWideViewPort = true //任意比例缩放
webView.webViewClient = webClient
webView.webChromeClient = webChromeClient
}
private var webClient: WebViewClient = object : WebViewClient() {
//处理网页加载失败时
override fun onReceivedError(
view: WebView,
errorCode: Int,
description: String,
failingUrl: String
) {
showErrorView(true) //显示错误页面
}
}
private var webChromeClient: WebChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress >= 100) {
view.visibility = View.VISIBLE
}
}
}
private fun showErrorView(isToShow: Boolean) {
errorView.visibility = if (isToShow) View.VISIBLE else View.GONE
}
}
网友评论