Android WebView is used to display the web pages in an android app and the web page can be loaded from the same application or URL. Therefore, In this tutorial, we will learn how to create a WebView in an Android application using Kotlin.
Android Kotlin WebView Complete Tutorial
In this article, we will work on few Android Webview Example projects.
After that, 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 an 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 the 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
Before, loading a URL into a WebView and view the webpage make sure you have internet permission. After that, set internet permission into android manifest uses-permission.
<uses-permission android:name="android.permission.INTERNET">
</uses-permission
Load HTML File in WebView:
Similarly, Loading existing .html files from the assets folder with android WebView is very simple.
After that, create an assets folder, and put the HTML file into it. The correct path for files stored in the assets folder is file:///android_asset/*
.
webview.settings.javaScriptEnabled = true
webview.loadUrl("file:///android_asset/**YOUR FILE NAME**.html")
How to enable javaScript for WebView:
Therefore, JavaScript is by default turned off in WebView widgets. Hence web pages containing javascript references won’t work properly. To enable the javascript support following snippet needs to be called on the Webview instance:
getSettings().setJavaScriptEnabled(true);
Android Webview Example With Progress Bar