Android WebView Using Kotlin With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Hello Readers! In this post, we are going to learn how to use android webView using kotlin in any android application. In this post, We will cover many topics such as –
   – 1. Different attributes of webView that can be used to customise it
   – 2. Define WebChromeClient to customise WebView
   – 3. Define WebViewClient to customise WebView
   – 4. Use WebSettings to customise WebView
   – 5. Load data in WebView from different sources like, file path, url, defined html etc.

We will see each topic one by one.

Output

Tutorialwing Android Kotlin WebView Output Android WebView Using Kotlin In Any Android Application WebView In Kotlin Tutorial With Example

Tutorialwing Kotlin WebView Output

Getting Started

WebView widget can be defined as below –

WebView is a widget that is used to display webpages in any android application. Using this class, you can also implement your own web browser or simply display online content within your activity in the application

Webkit rendering engine is used in webView to provide features such as –
   – 1. Display webpages
   – 2. Includes methods to navigate forward and backward through history.
   – 3. Zoom in zoom out
   – 4. Text Searches and many more things

Attributes of Android WebView Widget

Some of the popular attributes of android webView widget inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:clipChildren Specifies whether a child is limited to draw inside of its bounds or not
2 android:layoutAnimation Specifies the layout animation to use when the viewGroup is laid out for the first time
3 android:persistentDrawingCache Specifies the persistent of the drawing cache
4 android:layoutMode Specifies layout mode this viewGroup

Some of the popular attributes of android WebView inherited from View are –

Sr. XML Attributes Description
1 android:alpha Specifies alpha of the view
2 android:background Specifies drawable to be used for the background
3 android:contextClickable Specifies whether this view should react to context click event
4 android:elevation Specifies base z depth of the view
5 android:fitsSystemWindows It is used to adjust view layout based on system windows such as status bar etc. It accepts true or false value.
6 android:foreground Specifies the drawable to draw over the content
7 android:foregroundGravity Specifies the gravity of the foreground drawable



Example of Android WebView Widget

At first, we will create android application. Then, we will use WebView widget in this application.

1. Creating New Project

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as WebView. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly.

Now, we will modify xml and other files to access WebView using kotlin file in the application.

2. Modify Values folder

Open res/values/strings.xml file and add below code into it.

<resources>
	<string name="app_name">WebView</string>
	<string name="site_url">https://tutorialwing.com</string>
</resources>

Open res/values/styles.xml file and add below code into it.

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
	<!-- Customize your theme here. -->
	<item name="colorPrimary">@color/colorPrimary</item>
	<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
	<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

We are not showing toolBar in the application. So, we have changed the parent theme to Theme.AppCompat.Light.NoActionBar.

Open res/values/colors.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
	<color name="colorPrimary">#0b6c63</color>
	<color name="colorPrimaryDark">#0a6058</color>
	<color name="colorAccent">#FF4081</color>
</resources>

3. Internet Permission in AndroidManifest file

Since we are going to load webpage in the webView, we also need permission to access internet. So, add internet permission in AndroidManifest.xml file. Add below code into src/main/AndroidManifest.xml file –

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.webview"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<uses-permission android:name="android.permission.INTERNET" />

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">

		<meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
				   android:value="false" />

		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

Whenever you use webView in application, it uploads some anonymous data to google. These data are used to improve this webView widget. If you do not want to let webView to upload data to google, you need to add meta-data in < application > element in manifest file.

<manifest>
     <application>
         ...
         <meta-data android:name="android.webkit.WebView.MetricsOptOut"
             android:value="true" />
     </application>
 </manifest>

Note – Data is uploaded to google only if user has given permission and app has not opted out.

While using webView, if you want to block malicious url and show a warning UI to either navigate back or proceed to malicious url, you need to add below meta-data in < application > element in manifest file.

<manifest>
     <application>
         ...
         <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
             android:value="false" />
     </application>
</manifest>

4. How To Customise WebView Using Kotlin

We can customise webView in below ways –
(1) By Using WebViewClient class – Use this class when you want to deal with content rendering in the page. For example, error or form submission in the page.
(2) By Using WebChromeClient class – Use this class when you want to deal with user interface. For example, progressBar or javascript alert.
(3) By Using WebSettings – This class is used for work like enabling javascript, zoom-in or zoom-out feature in the page.
(4) By Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method so that it can accessed by javascript in the page.

4.1 Define WebChromeClient class For WebView Using Kotlin

Whenever you change something in webView that impact browser ui, then, this class is called. For example, Show progressBar while page is being loaded, Show javascript alert message etc.

So, create a class file (with name WebChromeClt.kt), subclassed form WebChromeClient, in main/java/com.tutorialwing.webview folder. Then, add below code into it.

package com.tutorialwing.webview

import android.app.Activity
import android.webkit.WebChromeClient
import android.webkit.WebView

class WebChromeClt internal constructor(private val activity: Activity) : WebChromeClient() {

    override fun onProgressChanged(view: WebView, progress: Int) {
        // Activities and WebViews measure progress with different scales.
        // The progress meter will automatically disappear when we reach 100%
        activity.setProgress(progress * 1000)
    }
}

Here, we are showing progressBar while page is loading.

4.2 Define WebViewClient For WebView Using kotlin

Whenever you change something in webView that impacts content rendering, then, it is called. For Example, Showing Error message in Form Submission etc.

So, create a class file (with name WebViewClt.kt), subclassed form WebViewClient, in main/java/com.tutorialwing.webview folder. Then, add below code into it.

package com.tutorialwing.webview

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.annotation.RequiresApi
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast

class WebViewClt internal constructor(private val activity: Activity) : WebViewClient() {

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
        val url: String = request?.url.toString();

        if (url.contains("https://tutorialwing.com", false))
            return false

        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        activity.startActivity(intent)
        return true
    }

    override fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean {
        if (url.contains("https://tutorialwing.com"))
            return false

        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
        activity.startActivity(intent)
        return true
    }

    override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
        Toast.makeText(activity, "Got Error! $error", Toast.LENGTH_SHORT).show()
    }
}

Here, we have used below methods –
– 1. shouldOverrideUrlLoading( . . . ) – Use this method when you want webBrowser to decide how a new url will be loaded. If this method returns false, it means current webView will handle the url. If this method returns true, it means host application will handle the url. If you have not used this method, webView will ask activity manager to provide proper handler for new url.

– 2. onReceivedError( . . .) – This method reports web resource loading error to the host application.

4.3 Use WebSetting to Customise WebView Using Kotlin

Whenever webView is created, a default settings is attached with it throughout it’s lifecycle. That’s destroyed only when webView is destroyed. If you webView is destroyed, any call using webSettings will return IllegalStateException.
So, you can manage settings of webView using webView.

You can perform below task using webSettings –
(a) You can enable javascript. You can do it as below –

val webSettings = webView!!.settings
webSettings.javaScriptEnabled = true

(b) You can enable built-in zoom. You can do it as below –

val webSettings = webView!!.settings
webSettings.builtInZoomControls = true

5. Use WebView Widget in xml file

Open res/layout/activity_main.xml file. Then, add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<WebView
		android:id="@+id/webView"
		android:layout_width="match_parent"
		android:layout_height="match_parent"/>

</LinearLayout>

In activity_main.xml file, we have defined WebView widget. Now, we will access this webView using kotlin file in the application. Then, we will perform some operations on it.

6. Load Data Into WebView Using Kotlin From Different Sources

We can load a page in WebView in below ways –
(a) A Page with given url.
(b) Create your own html page and load it into webView.
(c) Create a webpage by using data stored locally and then load it into webView.

Now, we will go through each way one by one.

6.1 Load WebPage With Given URL into WebView Using Kotlin

Open src/main/java/com.tutorialwing.webview/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.webview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.Window
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    private var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.requestFeature(Window.FEATURE_PROGRESS)

        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webView)
        if (webView != null) {

            val webSettings = webView!!.settings
            webSettings.javaScriptEnabled = true

            webSettings.builtInZoomControls = true

            webView!!.webViewClient = WebViewClt(this)
            webView!!.webChromeClient = WebChromeClt(this)

            //			 Case 1 .. Direct Url of the page...
            webView!!.loadUrl(getString(R.string.site_url))
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && this.webView!!.canGoBack()) {
            webView!!.goBack()
            return true
        }

        return super.onKeyDown(keyCode, event)
    }
}

Here, loadUrl(…) method has been used to load webpage into webView. getString(R.string.site_url) returns the url of the webpage to be loaded.

6.2 Create Custom HTML WebPage And Load into WebView Using Kotlin

Open src/main/java/com.tutorialwing.webview/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.webview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.Window
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    private var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.requestFeature(Window.FEATURE_PROGRESS)

        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webView)
        if (webView != null) {

            val webSettings = webView!!.settings
            webSettings.javaScriptEnabled = true

            webSettings.builtInZoomControls = true

            webView!!.webViewClient = WebViewClt(this)
            webView!!.webChromeClient = WebChromeClt(this)

            //	Case 2 .. Create your own html page...
            webView!!.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8")
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && this.webView!!.canGoBack()) {
            webView!!.goBack()
            return true
        }

        return super.onKeyDown(keyCode, event)
    }
}

Here, loadData(…) method has been used to load custom HTML data into webView.

6.3 Show Data of Given File Path into WebView Using kotlin

Open src/main/java/com.tutorialwing.webview/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.webview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.Window
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    private var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.requestFeature(Window.FEATURE_PROGRESS)

        setContentView(R.layout.activity_main)

        webView = findViewById(R.id.webView)
        if (webView != null) {

            val webSettings = webView!!.settings
            webSettings.javaScriptEnabled = true

            webSettings.builtInZoomControls = true

            webView!!.webViewClient = WebViewClt(this)
            webView!!.webChromeClient = WebChromeClt(this)

            //	Case 3 .. Show data in the file path...
            var html = "<html><head><title>TITLE!!!</title></head>"
            html += "<body><h3>Tutorial by tutorialwing.com</h3><img src=\"ic_launcher.png\" /></body></html>"

            // Provide relative url to the base...
            val baseUrl = "file:///android_res/mipmap/"
            val data = html
            val mimeType = "text/html"
            val encoding = "UTF-8"
            val historyUrl: String? = null

            webView!!.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && this.webView!!.canGoBack()) {
            webView!!.goBack()
            return true
        }

        return super.onKeyDown(keyCode, event)
    }
}

Here, we have used loadDataWithBaseURL(…) method to load data from local file into webView.

In this tutorial, we have shown many ways to load data into android webView. However, you can use any way based on your requirements to load data into webView.

For the sake of completeness of this tutorial, we have used method 1 (load data into webView with given url). When we run the program, we will get output as shown above.

That’s end of tutorial on Android WebView using kotlin.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners