我正在尝试覆盖WebView的下载侦听器,以使其能够在外部浏览器中打开不属于我们的网站,而不是将其加载到Webview中。事情是,我想将代码简化成这样]
webView?.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
if (!url.contains("mydomain")) {
CLog.v("InternalWebviewFragment.configWebView().setDownloadListener() isNOTmydomain url: $url")
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
activity?.startActivity(i)
}else{
super(url, userAgent, contentDisposition, mimetype, contentLength)
}
}
但是,我打算对确实属于我们域的url进行super的调用时说,该调用只能在点的左手使用。当我尝试键入
super.onDownloadStart
给出unresolved reference error
。
当网址是我们域的一部分时,如何使Webview侦听器照常营业?超级调用仅在非lambda方法中可用吗?
经过许多测试,@ Demigod的方法被证明是正确的方法。它只是需要同时使用应弃用的和应有的ShouldOverrideUrlLoading当前方法,here
// APIs up to 23 need this method
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
if (!url.contains("mydomain")) {
// InternalWebviewFragment external (non mydomain) urls will be dispatched to an external browser
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoadingOLD() isNotmydomain url: $url")
val i = Intent(Intent.ACTION_VIEW, Uri.parse(url))
activity?.startActivity(i)
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoadingOLD() isNotmydomain After Intent")
return true //InternalWebviewFragment this avoids the webview to load the url we've just sent to the browser
}
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoadingOLD() ismydomain url: $url")
// mydomain urls should load fine in the webview
view?.loadUrl(url)
return super.shouldOverrideUrlLoading(view, url)
}
// for APIs 24+
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
if (!request?.url.toString().contains("mydomain")) {
// InternalWebviewFragment external (non mydomain) urls will be dispatched to an external browser
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoading2() isNotmydomain url: ${request?.url.toString()}")
val i = Intent(Intent.ACTION_VIEW, Uri.parse(request?.url.toString()))
activity?.startActivity(i)
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoading2() isNotmydomain After Intent")
return true //InternalWebviewFragment this avoids the webview to load the url we've just sent to the browser
}
CLog.v("InternalWebviewFragment.getSimpleWebViewClientUrlLoading().shouldOverrideUrlLoading() ismydomain url: $url")
// mydomain urls should load fine in the webview
view?.loadUrl(request?.url.toString())
return super.shouldOverrideUrlLoading(view, request)
}