Display Web View in Android

Display Web View in Android

A web view can be used to display web pages inside an 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 the user clicks on any link in the WebView, the 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.WebView
import android.webkit.WebViewClient

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

        val webView: WebView = findViewById(R.id.webView)
        webView.settings.javaScriptEnabled = true
        webView.webViewClient = WebViewClient()
        webView.loadUrl("https://lindevs.com")
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.