Android WebView Example

Total Views : 160
Zoom In Zoom Out Read Later Print

WebView allow you to display web content or you can say full web page as part of your activity layout, but lack some of the features of fully developed browser. A WebView is useful when you need increased control over the UI, for example which page user can visit in you app and advanced configuration options that will allow you to embed web pages in a specially designed environment for your application.

Android WebView component is a full-fledged browser implemented as a View subclass to embed it into our android application.

Use of Android WebView

As you know we can use TextView to show some html text using fromHtml method of Html class. But what if we want to show an entire web-page  or lots of formatted text then TextView is not a option.

A common scenario in which using WebView is helpful is when you want to provide information in your app that will be change in time or you might need to update it frequently or most of time it will change, such as privicy policy, an end user agreement or faq, a user guide. Within your Android app, you can create an Activity that contains a WebView, then use that to display your document that's hosted online using URL of your document.

Creating a WebView Example Project

First of all we need to create a view in xml of our activity or fragment.

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

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

</RelativeLayout>

Required Permission

AndroidManifest.xml

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

MainActivity.java

package com.prodevsblog;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    void init() {
        WebView webView = findViewById(R.id.webView);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}

Code Break

1. Get reference of xml webview to java.

WebView Reference

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

2. Setting JavaScript enabled because JavaScript is disabled by default

Enable JavaScript

WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

3. Loading URL in WebView

loadUrl()

webView.loadUrl("https://prodevsblog.com");

Using WebViewClient

By default when you load url or a user clicks on a link inside the opened webpage open the systems default browser app. This can break the user experience of the app users or app flow we want to keep. for this we need to create a WbViewClient then override shouldOverrideUrlLoading() method.

MyWebViewClient.java

package com.prodevsblog;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyWebViewClient extends WebViewClient {

    // Deprecated Method
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(url.contains("prodevsblog.com"))
            return false;

        return super.shouldOverrideUrlLoading(view, url);
    }

    // Use this for new App
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        Uri uri = request.getUrl() ;
        if(uri.getHost() != null ) {

            if(uri.getHost().endsWith("prodevsblog.com")) {
                //The current WebView handles the url.
                return false;
            }

            if(uri.getHost().endsWith("google.com")) {
                //The host application wants to leave the current WebView and handle the url itself.
                return true;
            }

        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(request.getUrl().toString()));
        view.getContext().startActivity(intent);
        return true;

    }
}

setWebViewClient()

webView.setWebViewClient(new MyWebViewClient());

Navigation In WebView

You can use back button key event for going back to previous page in webview. use one of these as you see fit.

onKeyDown(int keyCode, KeyEvent event)

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
	if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
		this.webView.goBack();
		return true;
	}

	return super.onKeyDown(keyCode, event);
}

onBackPressed()

@Override
public void onBackPressed() {
    if (this.webView.canGoBack()) {
        this.webView.goBack();
        return ;
    }
    super.onBackPressed(); // Finish if last page in history
}

MainActivity Final Code

MainActivity.java


package com.prodevsblog;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    void init() {
        webView = findViewById(R.id.webView);

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.setWebViewClient(new MyWebViewClient());

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

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.webView.canGoBack()) {
            this.webView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    /*
    @Override
    public void onBackPressed() {
        if (this.webView.canGoBack()) {
            this.webView.goBack();
            return ;
        }
        super.onBackPressed(); // Finish if last page in history
    }
    */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_setting, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}

More Ways to use WebView and load data.

Custom

//load webview with direct html code
webView.loadData("<html><body>Pro Devs Blog!</body></html>", "text/html", "UTF-8");

//////////////////////////////////////////
// load url with custom data;
String baseUrl    = "https://prodevsblog.com";
String data       = "Custom Data Link";
String mimeType   = "text/html";
String encoding   = "UTF-8";
String historyUrl = "https://prodevsblog.com";

webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);

You can download android project from below link.

See More

Latest Photos