Advertisement
Guest User

MainActivity.kt

a guest
Jun 26th, 2020
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.70 KB | None | 0 0
  1. package org.example.tortotrulo
  2.  
  3. import android.content.Intent
  4. import android.net.Uri
  5. import androidx.appcompat.app.AppCompatActivity
  6. import android.os.Bundle
  7. import android.webkit.WebView
  8. import android.webkit.WebViewClient
  9. import androidx.core.content.ContextCompat
  10. import kotlinx.android.synthetic.main.activity_main.*
  11.  
  12. class MainActivity : AppCompatActivity() {
  13.  
  14.     //a WebViewClient that accepts all www.cake.co URLs and displays them, but relegates
  15.     //other URLs to the system's default browser
  16.     private class CakeWebViewClient : WebViewClient() {
  17.         override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
  18.             if (Uri.parse(url).host == "www.cake.co") {
  19.                 //false for all URLs under the cake.co host, these will open in app
  20.                 return false
  21.             }
  22.  
  23.             //external link, launch another Activity that handles URLs
  24.             if (view?.context != null) {
  25.                 Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
  26.                     ContextCompat.startActivity(view.context,this,null)
  27.                 }
  28.             }
  29.             return true
  30.         }
  31.     }
  32.  
  33.     override fun onCreate(savedInstanceState: Bundle?) {
  34.         super.onCreate(savedInstanceState)
  35.         setContentView(R.layout.activity_main)
  36.  
  37.         //use a WebViewClient that opens all cake.co URLs in the view,
  38.         //but opens external web content elsewhere (e.g. Chrome)
  39.         webview.webViewClient = CakeWebViewClient()
  40.  
  41.         //enable JS for functionality like Follow/Signin to work
  42.         webview.settings.javaScriptEnabled = true
  43.  
  44.         //load some cake.co content
  45.         webview.loadUrl("https://www.cake.co/")
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement