Display Web View in Android

A web view allows to display web pages inside application without opening a browser. Web view only displays a page and does not provide the browser features, such as an address bar, navigation controls, etc.

A WebView class is used to create a web view.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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=".MainActivity">

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

</RelativeLayout>

Application should have Internet access. So we need to request the INTERNET permission in the manifest file.

app/src/main/AndroidManifest.xml

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

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

    <application>
        ...
    </application>

</manifest>

The method loadUrl() is used to load a web page in the WebView. By default, JavaScript is disabled. It can be enabled through the WebSettings.

By default, if user clicks on any link in the WebView, web page will not be loaded inside your application. So we need to provide a WebViewClient for WebView.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebViewClient
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webView.settings.javaScriptEnabled = true
        webView.webViewClient = WebViewClient()
        webView.loadUrl("https://lindevs.com")
    }
}

Leave a Comment

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