我有一个 webView 和 3 个按钮,显示 3 个不同的 url。如果我按下显示 url_1 的第一个按钮,当我按下后退按钮并完成它并返回到 Activity 时,一切都很好。但是,当我按第二个按钮显示 url_2 时,会短暂出现 url_1,然后出现 url_2。当我按背面时,它从 url_2 转到 url_1,然后返回到活动。无论我按下按钮的顺序如何,都会发生此问题,这意味着如果我按下 url_3 的第三个按钮,每当我按下其他 2 个按钮时,在它们的网址显示之前,它总是会首先短暂出现。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.button1.setOnClickListener {
loadWebViewWith("first_url")
}
binding.button2.setOnClickListener {
loadWebViewWith("second_url")
}
binding.button3.setOnClickListener {
loadWebViewWith("third_url")
}
}
fun loadWebViewWith(urlStr: String) {
binding.webView.visibility = View.VISIBLE // shows the webView in the current activity
binding.webView.settings.javaScriptEnabled = true
binding.webView.settings.loadWithOverviewMode = true
binding.webView.settings.useWideViewPort = true
clearWebViewCache()
binding.webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest? ): Boolean {
request?.url?.let {
view?.loadUrl(it.toString())
}
return true
}
@Deprecated("Deprecated in Java")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
url?.let {
view?.loadUrl(it)
}
return true
}
}
binding.webView.loadUrl(urlStr)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (event.getAction() === KeyEvent.ACTION_DOWN) {
when (keyCode) {
KeyEvent.KEYCODE_BACK -> {
if (binding.webView.canGoBack()) {
binding.webView.goBack()
} else {
if (binding.webView.visibility == View.GONE) {
finish()
} else {
binding.webView.visibility = View.GONE // hides the webView in the current activity
clearWebViewCache()
}
}
return true
}
}
}
return super.onKeyDown(keyCode, event)
}
fun clearWebViewCache() { // I tried these in different combinations
binding.webView.clearCache(true)
binding.webView.clearFormData()
binding.webView.clearHistory()
binding.webView.clearSslPreferences()
binding.webView.loadUrl("about:blank")
binding.webView.reload()
binding.webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
WebStorage.getInstance().deleteAllData()
CookieManager.getInstance().removeAllCookies(null)
CookieManager.getInstance().flush()
this.deleteDatabase("webview.db")
this.deleteDatabase("webviewCache.db")
}