美文网首页安卓开发
安卓替换webview默认报错页面

安卓替换webview默认报错页面

作者: 蓝不蓝编程 | 来源:发表于2021-01-18 17:03 被阅读0次

目标

替换掉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
    }
}

源代码

https://gitee.com/cxyzy1/webviewErrorPageReplacement

相关文章

网友评论

    本文标题:安卓替换webview默认报错页面

    本文链接:https://www.haomeiwen.com/subject/bxpxzktx.html