ZOFTINO.COM android and web dev tutorials

Android WebView Tutorial

If you have a website and you want to display pages of your website in your android app, you can do so using android WebView widget. Android WebView displays HTML content from a URL or html text.

You can customize or configure WebView using WebChromeClient, WebViewClient, and WebSettings classes.

You can use WebChromeClient class to handle browser UI related events such as java script alert dialog, permission request, for enabling video full screen and progress change, etc and provide custom behavior. You can use WebViewClient to handle content rendering events such as errors, form submission, page start, page finish, too many redirects, before loading a url, etc and provide custom behavior. WebSettings can be used to enable java script and safe browsing, customize font, set cache and enable saving form data and passwords etc.

Android WebView

If you want to load html page of a website in WebView, you need to request for internet permission by adding uses-permission entry to manifest.xml file.

To use WebView, first define WebView element in xml layout and then in the activity add URL to be loaded to WebView by calling loadUrl method on WebView object. If you just call loadUrl, the page will open in default browser. To prevent this behavior of page being opened in browser, you need to create an instance of WebViewClient and set it to WebView.

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    tools:context=".WebViewActivity">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar"/>
</android.support.constraint.ConstraintLayout>
public class WebViewActivity  extends AppCompatActivity {

    private WebView wView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_layout);

        wView = findViewById(R.id.webView);
        wView.loadUrl("https://en.wikipedia.org");
        wView.setWebViewClient(new WebViewClient());

    }
}
android webview page loading example

To load html text in WebView, you can use loadData method on webview object passing html string to it, below code and screen shot shows using WebView.

myToolbar.setSubtitle("html text example");

wView = findViewById(R.id.webView);

String htmlText = "<html><body><h3>Hello WebView</h3>"+
        "<p>This tutorial shows how to use web view.</p></body></html>";
wView.loadData(htmlText, "text/html", null);
android webview example

Enabling JavaScript in WebView

By default WebView doesn’t process java script. If you have a web page with java script, you need to enable java script in WebView in order for the page to work as expected. You can enable JavaScript in WebView using WebSettings object which contains default settings and can be obtained by calling getSetting method on web view object. Then you need to call setJavaScriptEnabled method on web setting object passing true as argument to it to enable java script.

wView = findViewById(R.id.webView);
WebSettings webSettings = wView.getSettings();
webSettings.setJavaScriptEnabled(true);

WebView Text Size

To set text size or zoom of the page, call setTextZoom method on WebSetting object passing percent as arugment.

WebSettings webSettings = wView.getSettings();
        webSettings.setTextZoom(200);

WebView Settings

You can use WebSettings object to configure WebView. Some of the important setting methods are setSaveFormData, setSafeBrowsingEnabled, setMinimumFontSize, setLoadsImagesAutomatically, setAppCacheMaxSize, setAppCacheEnabled, setCacheMode, setBlockNetworkImage and setBlockNetworkLoads.

Calling JavaScript Method in WebView

If you have java scripts that you want to run asynchronously in web view without reloading the current page, you can do so by using evaluateJavascript method, passing java script to be run and setting call back method to be called after completion of java script execution.

 String jsFunction = "(function() { return 'Hello JS'; })();";

wView.evaluateJavascript(jsFunction, new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Toast.makeText(WebViewActivity.this, ""+s, Toast.LENGTH_SHORT).show();
    }
}); 

WebView Handling Links or Page Navigation

By default, when a link on a page which is displayed in webview is clicked, android opens an app which handles the URL associated with the link.

The default behavior makes sense if the link is an external link. If your web page contains internal links, you may want to display the page in webview itself. To change the default behavior, you need to extend WebViewClient class, override shouldOverrideUrlLoading method and return true of false checking the url host, false tells the system to open the link in web view.

 public class WebViewActivity  extends AppCompatActivity {

    private WebView wView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_layout);

        wView = findViewById(R.id.webView);
        WebSettings webSettings = wView.getSettings();
        webSettings.setJavaScriptEnabled(true); 

        String htmlText = "<html><body><h3>Hello WebView</h3> " +
                "<a href=\"http://www.zoftino.com\">internal link</a>"+
                "<p>This tutorial shows how to use web view.</p>" +
                "<a href=\"https://www.google.com\">external link</a></body></html>";
        wView.loadData(htmlText, "text/html", null);

        wView.setWebViewClient(new ZoftinoWebViewClient());
    }
    private class ZoftinoWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals("www.zoftino.com")) {
                //if internal link, open in webview
                return false;
            }

            //else open in default app which is a browser
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    }
}

WebView Back Button or Viewing Previous Web Pages

WebView maintains history of visited web pages. You can navigate to pages in the WebView history by using goBack, goForward and goBackOrForward methods of WebView. To check whether WebView has back or forward history, you can use canGoBack and canGoForward methods.

You can implement your own navigation buttons or use android system back buttons to provide back button functionality.

To handle android system back button click events, you need to use onKeyDown method. In the method, call goBack method on web view to visit previous pages. Similarly, you can provide option to navigate forward.

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

WebView Handling Orientation Changes

When the device orientation changes from landscape to portrait or portrait to landscape, android will restart the current activity. If current activity contains web view showing a web page, by default the page will be reloaded on orientation change.

If you don’t want this behavior, you can inform the system that activity will handle configuration changes itself by setting configChanges attribute of the activity in android manifest file. So to prevent activity restart when orientation changes, set configChanges to orientation|screenSize. With below setting, page in WebView will not be reloaded on orientation change.

 <activity android:name=".WebViewActivity"
    android:configChanges="orientation|screenSize"></activity> 

If you want to make activity do something when configuration changes, you will have to implement onConfigurationChanged() method in activity.

 @Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //do something for land scape
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        //do something for portrait scape
    }
}