Kotlin: 1.2.71
Android Studio: 3.2.1
#WebView
It's a view for showing webpage
Official information: https://developer.android.com/reference/android/webkit/WebView
##Before using
You must add internet permission on AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
##Load webpage
Simply
webView.loadUrl("URL")
Layout (at least needed to show WebView on Fragment) :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.WebViewSampleFragment">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Here is an example of loading google.com. (Customized with toolbar
##Set some options
Add the options you want to add.
webView.apply {
settings.apply {
javaScriptEnabled = true
setSupportZoom(true)
loadWithOverviewMode = true
useWideViewPort = true
domStorageEnabled = true
}
webChromeClient = WebChromeClient()
webViewClient = WebViewClient()
}
Using .apply makes you and others easier to read the code.
##Control WebView
Go Back
webView.goBack()
Also, you can check canGoBack by
webView.canGoBack()
Go Forward
webView.goForward()
Also, you can check canGoForward by
webView.canGoForward()
###Reload
webView.reload()
##Handling WebView
###shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
This is a example of when a URL is about to be loaded in the current WebView.
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return true
}
}
#Project:
Code: https://github.com/GalaxyDevGamer/Android-Samples/blob/master/app/src/main/java/galaxysoftware/androidsamples/fragment/WebViewSampleFragment.kt
Layout: https://github.com/GalaxyDevGamer/Android-Samples/blob/master/app/src/main/res/layout/webview_layout.xml