BCA / B.Tech 8 min read

Integrating Web Content with WebView

Integrating Web Content with WebView

What is a WebView?

A WebView is a View in Android that allows you to display web pages (like HTML, CSS, and JavaScript) directly inside your application.

It acts as a mini-browser that is part of your activity's layout. By using it, the user doesn't need to leave your app and go to an external browser (like Chrome) to view web content.

Why Use WebView?

  • Displaying Help/Documentation: To show a help section or documentation within your app.
  • Terms and Conditions: To show users a "Terms and Conditions" or "Privacy Policy" page.
  • Simple Web Pages: When a part of your app is built using web technologies.

How to Use WebView

Step 1: Add Internet Permission

A WebView needs internet access to load web pages. Therefore, you must add the internet permission to your `AndroidManifest.xml` file.


<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

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

    <application ...>
        ...
    </application>
</manifest>

Step 2: Add WebView to the XML Layout


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

Step 3: Load a Web Page in the Activity

In your activity's Java file, find the `WebView` and load a web page using the `loadUrl()` method.


public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

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

        myWebView = (WebView) findViewById(R.id.my_web_view);
        myWebView.loadUrl("https://www.google.com");
    }
}

Enabling JavaScript

For security reasons, JavaScript is disabled by default in a WebView. If the web page you are loading uses JavaScript, you must manually enable it.


// Inside the onCreate() method
myWebView = (WebView) findViewById(R.id.my_web_view);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true); // Enable JavaScript
myWebView.loadUrl("https://www.google.com");

Handling Navigation (WebViewClient)

The Problem: By default, when a user clicks a link inside a WebView, Android opens that link in the device's default browser, not within your app.

The Solution: To change this behavior, you need to provide the `WebView` with a custom `WebViewClient`. A `WebViewClient` allows you to intercept URL loading.


// Inside the onCreate() method
myWebView = (WebView) findViewById(R.id.my_web_view);
myWebView.setWebViewClient(new WebViewClient()); // This line keeps navigation inside the app
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://www.google.com");

Now, when the user clicks a link, the page will open in the same WebView.