Skip to content
Related Articles

Related Articles

How to use WebView in Android
  • Last Updated : 18 Feb, 2021
public class WebView 
extends AbsoluteLayout 
implements 
    ViewTreeObserver.OnGlobalFocusChangeListener, 
    ViewGroup.OnHierarchyChangeListener

WebView is a view that display web pages inside the application. It is used to turn the application into a web application.

Class Hierarchy :

java.lang.Object
   ↳  android.view.View
        ↳  android.view.ViewGroup
             ↳  android.widget.AbsoluteLayout
                  ↳  android.webkit.WebView

MainActivity.java




package com.example.hp.webview;
  
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
          
        // Binding MainActivity.java with 
        // activity_main.xml file
        setContentView(R.layout.activity_main);
          
        // Find the WebView by its unique ID
        WebView w = (WebView) findViewById(R.id.web);
          
        // loading http://www.google.com url in the the WebView.
        w.loadUrl("http://www.google.com");
          
        // this will enable the javascipt.
        w.getSettings().setJavaScriptEnabled(true);
          
        // WebViewClient allows you to handle 
        // onPageFinished and override Url loading.
        w.setWebViewClient(new WebViewClient());
          
    }
}

 
activity_main.xml

In the xml file only use of WebView is made inside RelativeLayout.






<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hp.webview.MainActivity">
  
    <WebView
        <!-- covers 368dp width as required. -->
        android:layout_width="368dp"
          
        <!-- unique ID of WebView -->
        android:id="@+id/web"
          
        <!-- covers 495dp height as required. -->
        android:layout_height="495dp"
          
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp" />
</RelativeLayout>

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

"uses-permission android:name="android.permission.INTERNET"

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :