Android Kotlin WebView Tutorial

In this tutorial we will learn how to crate a WebView in Android application using Kotlin.

In this article we will work on few Android Webview Example projects.

We will know the best practice of different types of Android Webview Settings. How android webview browser load html from assets folder.

How to Add WebView in Android Layout

You can easily add a WebView layout into a activity or fragment. Just copy this code.

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

How to add WebView Programmatically

Make a WebView object and show it through setContentView() method.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle
import android.webkit.WebView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
    
       //make a webview object
       val webview= WebView(this)
       //show it through setcontentview()method
       setContentView(webview)
        
    }
}

How to Load Web URL in Android WebView

To load a url into a Android WebView make sure internet permission is enable.

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

Load HTML File in WebView

Loading existing .html file from assets folder with android WebView is very simple.

First of all create a assets folder then put the .html file into it.

The correct path for files stored in assets folder is file:///android_asset/*.

webview.settings.javaScriptEnabled = true
webview.loadUrl("file:///android_asset/**YOUR FILE NAME**.html")

Android Kotlin Webview Example With Progress Bar

Leave a Comment

Your email address will not be published. Required fields are marked *