WebView in Android

In this tutorial, we will learn how to use a WebView in Android. We use WebView to show webpages in Android. Using WebView you can load a web page from the same application or you can load a web page from any URL. To use web view in android you must have internet permission in your android manifest file. In this tutorial, we will learn how to add WebView in Android XML file and how to load URL in this WebView using our Java file.

Before doing anything we will add internet permission in our AndroidManifest.xml file. Because without Internet permission our web view will not work.

Add in Manifest file:

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

Now we will move to our next step. So start with our XML file. In this step, we will add a Web View widget in our activity.

XML Code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</LinearLayout>

After adding this XML code in XML layout file add this code to Java file where we will write code to load a web page in our WebView.

Java Code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       final WebView webView=findViewById(R.id.webView);

       webView.loadUrl("https://www.google.com");
    }
}

After adding this code in Java file run project and you will get Google Home page on your activity because we have written URL of google in loadURL method of WebView class. Here you can try to load different URLs. Check Output of this project.

Output:

Spread the love
Scroll to Top
×