Android WebView with kotlin - android kotlin example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="visible" ></WebView>
</LinearLayout>
MainActivity.kt
import android.app.*
import android.content.*
import android.graphics.*
import android.net.*
import android.os.*
import android.support.v7.app.*
import android.util.*
import android.webkit.*
class MainActivity : AppCompatActivity() {
private var webView: WebView? = null internal lateinit var progressDialog: ProgressDialog
internal var url = "https://www.google.com"
override fun onBackPressed() {
if (webView!!.canGoBack()) {
webView!!.goBack()
} else {
super.onBackPressed()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webView = findViewById(R.id.webview)
webView!!.settings.javaScriptEnabled = true webView!!.settings.builtInZoomControls = true webView!!.settings.setSupportZoom(true)
webView!!.settings.loadWithOverviewMode = true webView!!.loadUrl(url)
webView!!.webViewClient = MyWebViewClient()
}
inner class MyWebViewClient : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
Log.d("url", "url==" + url)
progressDialog = ProgressDialog(this@MainActivity)
progressDialog.setTitle("Loading...")
progressDialog.setMessage("Please wait.")
progressDialog.setCancelable(true)
progressDialog.isIndeterminate = true progressDialog.setCanceledOnTouchOutside(false)
progressDialog.show()
}
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest?): Boolean {
if (request != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
view.loadUrl(url)
}
return true } else {
return false }
}
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true }
override fun onPageFinished(view: WebView, url: String) {
if (progressDialog.isShowing) {
progressDialog.dismiss()
webView!!.isEnabled = true }
}
}
}
Comments
Post a Comment