Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Android WebView in Kotlin

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let’s display the inside the Android Application using Kotlin.

Note: To implement Android WebView in Java please refer How to use WebView in Android using Java.

Class Hierarchy



Step 1: Create a new project 

To create a new project in android studio please refer, how to Create/Start a New Project in Android Studio.

Remember to add these to your gradle(app) files

   id ''
   id 'kotlin-android'
   id 'kotlin-android-extensions'

Step 2: Modify activity_main.xml

This is used to set the front end of the Application, we place the WebView in the front end. 


    <!-- Place Web-view on the Screen -->

Step 3: Modify MainActivity.kt

This is the back end of the Application, here we assign values to the views and actions to the views.


package com.example.webview_kotlin
import android.os.Bundle
import android.webkit.WebViewClient
class MainActivity : AppCompatActivity() {
    private lateinit var webView: WebView
    override fun onCreate(savedInstanceState: Bundle?) {
        webView = findViewById(
        // WebViewClient allows you to handle
        // onPageFinished and override Url loading.
        webView.webViewClient = WebViewClient()
        // this will load the url of the website
        // this will enable the javascript settings, it can also allow xss vulnerabilities
        webView.settings.javaScriptEnabled = true
        // if you want to enable zoom feature
    // if you press Back button this code will work
    override fun onBackPressed() {
        // if your webview can go back it will go back
        if (webView.canGoBack())
        // if your webview cannot go back
        // it will exit the application

Step 4: Modify AndroidManifest.xml

In AndroidManifest.xml, one needs to include the below permission, in order to access the internet.


<?xml version="1.0" encoding="utf-8"?>
    <!-- Give permission for app to access the Internet -->
    <uses-permission android:name="android.permission.INTERNET"/>
       <activity android:name=".MainActivity">
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />

 Output: Run on Emulator

When we run the application either on the Emulator or on the Android Smartphone we can see this as our output. Remember to turn on the internet on your device.

output screen

My Personal Notes arrow_drop_up
Last Updated : 19 Apr, 2023
Like Article
Save Article
Similar Reads