Last Updated:

Working with WebView on Android: Sample and Feature Description

On Android, there are several ways to display HTML pages in your app. The most effective way is to use the Android WebView widget – we will talk about it today.

The component in Android is a full-fledged browser that is implemented as a subclass so we can easily embed it into our Android application.WebViewView,

 

Details about WebView in Android: what, how and why

 

Most often, a widget is used to work with simple html pages. In this case, we can implement a static method that belongs to the utility HTML class for parsing lines with html code and then displaying it in .

TextViewfromHtml()TextView

The widget provides simple formatting for styles (bold, italics), fonts, different colors, hyperlinks, etc.

TextView

However, with complex formatting and a large volume of HTML pages, the widget is no longer able to cope. For example, working with such functional and voluminous sites as Facebook or other social networks through will no longer work.TextViewTextView

In such cases, it comes to the rescue, since only it can handle large ubhams and a lot of HTML tags. Vision can also work with and , which the method would simply ignore.WebViewWebViewCSSJavaScriptHtml.fromHtml()

 

WebView also provides work with the history of visits and navigation back and forth through the pages.

 

However, it also has a whole set of drawbacks: in terms of the efficiency of memory consumption, it is significantly inferior. The reason for the large memory consumption is the web content rendering engine WebKit/Blink, which is still used in browsers such as Chrome.WebViewTextViewWebView

WebView Tutorial

Below is an example of working with the layout, installing the widget in code and an overview of the most useful methods when working with Android.WebView

1. Install the WebView in the layout

The component is inserted into the XML layout file where we want the widget to appear. Let's create a simple Hello World project on Android and see how it works in the layout:WebViewWebViewactivity_main.xml

2. Initialize Android WebView in code

The WebView component is initialized in the class , using the identifier previously defined in :MainActivityactivity_main.xml

3. Use the loadUrl() method

Once we have a link to the WebView, we can load some kind of site using the HTTP protocol. The method is used to load any URL into component , for example:WebViewloadUrl()WebView

Before we begin to explore further, there are two important points that should not be overlooked:WebView

  • JavaScript support: JavaScript is disabled by default in . Consequently, web pages containing JavaScript will not work properly. To enable it, use the following code snippet:Webview

 

 

  • Adding permissions: to upload a link to , we need to add permission to access the Internet in our application:WebViewAndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.p-qc.androiddev.hellowebviewapp">


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


<application
android:allowbackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>


</manifest>

Below is the class code with all the above considerations:MainActivity

Installing WebViewClient

 

The installation is necessary so that the user clicks on a link inside the web page of our application and this link opens in our application, and not by the default browser.WebViewClient

To keep the navigation links in our app with , we have to create a subclass and override the . Let's look at a simple example of a subclass: 

WebViewWebViewClientshouldOverrideUrlLoading (WebView webView, String url)WebViewClient

Here we can see that the method returns . This means that clicking on the link will open a tab inside our app, not the standard browser.shouldOverrideUrlLoading()false

And now let's change our application so that it opens only the links of the site https://www.p-qc.com, and when you click on the links of other sites, it asks which browser to use.

 

To do this, you need to add only one condition to the method:shouldOverrideUrlLoading()

 

package.com.p-qc.androiddev.hellowebviewapp;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.webkit.webview;
import android.webkit.WebViewClient;


public class SimpleWebViewClientImpl extends WebViewClient{


privateActivity activity = null;


public SimpleWebViewClientImpl(Activity activity) {
this.activity = activity;
}


@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
// all links containing 'p-qc.com'
// will be opened inside the application
if (url.contains("www.p-qc.com")){
return false;
}
// all other links will ask which browser to open
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
}

Navigating Inside an Android WebView: Pressing Forward and Backward Buttons

 

If we press the back button in the application we are developing, then we will see that the application returns to the home screen, even if we navigate through several pages within the . To use the link browsing history inside when we click the back button, we have to change the override function of that button:WebViewWebView

We override the method and now it checks first that it can go back to the previous link because it supports browsing history like a normal browser. If there are no links in the history, then clicking on the back button will work by default, that is, exit the application.

onKeyDown()WebViewWebView

Below is the whole code with the above features:MainActivity

Now run your app and follow the links inside the site. You'll see that all transitions occur within the app:

And all clicks on links that lead to other sites ask which application to open the link:

Loading Content into a WebView: Sources and Methods

In addition to clicking on links in, there are several other ways to download content that is provided by means of calling the method:WebViewloadUrl()

  • The method works by specifying a prefix to the reference and http://https://
  • And also: — opens a local filefile:///путьКфайлу
  • file:///android_asset/ — opens a file that is located in your app's folderassets
  • content:// – works with to retrieve content.ContentProvider

There is also a loadData() method, which takes a string with html code in the parameters, for example:

The WebView component has a large number of methods for working with links, history, and other elements, but we have considered the most used and useful methods. We also wrote a small application that opens within itself only the links of the site https://p-qc.com and asks how to open links to other sites.

 

If the article was useful to you, subscribe to new articles on Android and Java - ahead of you there are many interesting and useful articles on modern development!