10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android app development: Kotlin WebView

Posted at

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) :

webview_layout.xml
<?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
WebView Sample.jpg
##Set some options
Add the options you want to add.

WebViewSampleFragment.kt
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

10
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?