Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Methods of WebView
3.
Example of WebView
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Android WebView

Author Rahul Sain
1 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

WebView is a view in your program that displays web pages. You can also specify an HTML string and use WebView to display it within your application. WebView converts your application into a web-based application.

In this article, we will learn about WebView in Android. But before jumping into this, we would strongly recommend learning about Relative Layout.

The upcoming section will discuss various methods provided by WebView for displaying websites with the help of some examples.

Methods of WebView

To show a web page, Android WebView employs the WebKit engine. Safari, Mail, the App Store, and several other apps on macOS, Android, and Linux use the WebKit web browser engine. WebKit is the rendering engine used by Safari, and it was previously used by Google's Chrome browser. 

Let's look at some methods provided by the WebView that we will use while using it in our Android app.

  1. canGoBack(): This function indicates whether the WebView has a back history item.
  2. canGoForward()This function indicates whether the WebView has a forward history item.
  3. clearHistory()This function will clear the forward and backward history of the WebView.
  4. destroy()This function destroys WebView's internal state.
  5. findAllAsync(String find)This function finds and highlights all string occurrences.
  6. getProgress()This method retrieves the current page's progress.
  7. getTitle(): This method returns the current page's title.
  8. getUrl(): This method returns the current page's URL.

Note: If you click on a link within the WebView's webpage, the page will not be loaded inside your WebView. To accomplish this, extend your class from WebViewClient and override its function.

Syntax:

private class MyBrowser : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }

To load a web URL into the WebView, use the WebView class's loadUrl(String Url) method, passing in the appropriate URL.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of WebView

Here is an example of how to utilize WebView Layout. It produces a simple web application that prompts you for a URL and loads that URL's website in the WebView.

The changed main activity file MainActivity.kt is shown below.

Code:

package com.codingninjas.ui

import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    var button: Button? = null
    var editText: EditText? = null
    var webView: WebView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button = findViewById<View>(R.id.btn) as Button
        editText = findViewById<View>(R.id.eT) as EditText
        webView = findViewById<View>(R.id.wV) as WebView
        webView!!.webViewClient = MyBrowser()
        button!!.setOnClickListener {
            val url = editText!!.text.toString()
            webView!!.settings.loadsImagesAutomatically = true
            webView!!.settings.javaScriptEnabled = true
            webView!!.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
            webView!!.loadUrl(url)
        }
    }

    private class MyBrowser : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }
    }
}

Our main_activity.xml looks like the code snippet given below.

Code:

<?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"
    android:paddingLeft="8dp"
    android:paddingTop="8dp"
    android:paddingRight="8dp"
    android:paddingBottom="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="WebView"
        android:textSize="35sp" />

    <EditText
        android:id="@+id/eT"
        android:layout_width="280dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv"
        android:layout_alignParentStart="true"
        android:layout_marginTop="16dp"
        android:focusable="true"
        android:hint="Enter URL"
        android:importantForAutofill="auto"
        android:inputType="text"
        android:text="https://www.codingninjas.com/"
        android:textColorHighlight="#FD8EB4"
        android:textColorHint="#FF5252" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/eT"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/eT"
        android:text="Enter" />

    <WebView
        android:id="@+id/wV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btn"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true" />

</RelativeLayout>

And finally, we will use internet permission in our AndroidManifest.xml file to load URLs through the internet.

Code:

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.UI">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output:

    

To launch the website, enter a URL in the URL area and press the browse button that appears. But first, please make sure you're connected to the internet.

WebView will load the URL that the user will provide in EditText and only load if that is a valid URL. There may be some cases when some features can be easily implemented on the Web but not possible in Android to use this WebView.

FAQs

  1. Is WebView the same as Chrome?
    Ans: Chrome on Android is not the same as WebView. They share the same code, including a JavaScript engine and rendering engine.
     
  2. Which app uses WebView?
    Ans: Many well-known digital solutions that are marketed as app platforms are WebView apps. While most businesses do not publish their technology, we know that Meta, LinkedIn, Slack, Twitter, Gmail, the Amazon Appstore, and many others are WebView apps.
     
  3. What's the distinction between a WebView and a browser?
    Ans: A WebView is an embeddable browser that can be used by a native application to show web material, whereas a web app adds functionality and interactivity. Web apps run in browsers such as Chrome or Safari and take up no storage space on the user's device.

Key Takeaways

In this article, we have extensively discussed WebView in Android and its essential methods.

You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.

We hope that this blog has helped you enhance your knowledge regarding WebView and if you would like to learn more, check out our articles on VideoView. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Android Grid View
Next article
Android VideoView
Live masterclass