Daniel Fernandes
Android Enthusiast
So I was following the official guide on how to use WebView and I found a piece of code that I just can't get to work. Basically, if a URL the user clicked belongs to a particular domain (www.example.com), the WebView should open the link within itself. But if the URL is not part of the domain, then the link should be opened in an external browser of the users choice (by showing the thing where you pick your browser, and have the options 'Always' and 'Just once').
Here's my code:
I've been stuck on this for two days, couldn't find anything that worked. So I decided to show my entire code here so that one can see exactly where I went wrong, I know a lot of you are experts here. Any help will be very much appreciated!
Here's my code:
Code:
package com.cryptosonix.myapp
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.*
import androidx.core.content.ContextCompat.startActivity
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_ig_user1.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
web_user1.settings.javaScriptEnabled = true // web_user1 is the WebView
web_user1.settings.allowFileAccessFromFileURLs = true
web_user1.webViewClient = MyWebViewClient()
web_user1.loadUrl("https://example.com/page/")
//Starting another activity within the app works fine
settings_fab.setOnClickListener{startActivity(Intent(this, SettingsActivity::class.java))}
}
private class MyWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (Uri.parse(url).host == "www.example.com") {
return false
}
Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
startActivity(this) //Here's the problem!
}
//When I hover my mouse over 'this', a popup appears with the type mismatch error.
return true
}
}
}
I've been stuck on this for two days, couldn't find anything that worked. So I decided to show my entire code here so that one can see exactly where I went wrong, I know a lot of you are experts here. Any help will be very much appreciated!