Reputation: 560
I tried the codes from the forum all of which is in Java. It was converted to Kotlin by IDE but it's not working. I've just started learning Android. Please help me with this. I've attached the converted code below. Also, I added this -
val webUrl = webView.url
if (webUrl != null) {
shouldOverrideUrlLoading(webView,webUrl)
}
inside OnCreate. Not sure if that's correct or not. Below is the code---
private fun shouldOverrideUrlLoading(view: WebView, url: String) {
view.loadUrl(url)
if (url.startsWith("whatsapp://")) {
view.stopLoading()
try {
val whatsappIntent = Intent(Intent.ACTION_SEND)
whatsappIntent.type = "text/plain"
whatsappIntent.setPackage("com.whatsapp")
whatsappIntent.putExtra(
Intent.EXTRA_TEXT,
view.url.toString() + " - Shared from webview "
)
startActivity(whatsappIntent)
} catch (ex: ActivityNotFoundException) {
val makeShortText = "Whatsapp has not been installed"
Toast.makeText(this, makeShortText, Toast.LENGTH_SHORT).show()
}
}
}
Expecting your quick support. Thanks.
Upvotes: 1
Views: 2176
Reputation: 11
i had the same issue this is the solution i found
class KaboekieWebsite : AppCompatActivity() {
lateinit var myWebView: WebView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kaboekie_website)
myWebView = findViewById(R.id.KaboekieWebsiteView)
myWebView.webViewClient = WebViewClient()
myWebView.settings.setSupportZoom(true)
myWebView.settings.loadsImagesAutomatically
myWebView.settings.javaScriptEnabled = true
myWebView.setWebViewClient(Callback())
myWebView.loadUrl("https://www.Kaboekie.be/")
myWebView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
if (url.startsWith("intent://")) {
val intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
if (intent != null) {
val fallbackUrl = intent.getStringExtra("browser_fallback_url")
return if (fallbackUrl != null) {
webView.loadUrl(fallbackUrl)
true
} else {
false
}
}
}
else if (url.startsWith("tel:")){
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse(url)
startActivity(intent)
return true
}
else if (url.startsWith("mailto:")) {
val intent = Intent(Intent.ACTION_VIEW)
val data = Uri.parse(
url + Uri.encode("subject") + "&body=" + Uri.encode(
"body"
)
)
intent.data = data
startActivity(intent)
return true
}
return false
}
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event)
}
private class Callback : WebViewClient() {
override fun shouldOverrideKeyEvent(view: WebView?, event: KeyEvent?): Boolean {
return false
}
}
}
Upvotes: 1