WebView is a component that displays web content. It can display online content from the internet and can be used as a web browser to scroll and display content. It uses WebKit as the rendering engine to display web pages, including methods for zooming, searching text, and navigating forward and backward.
Note: To display online web pages or content in WebView, you need to add the internet permission in the AndroidManifest.xml file, as shown below:
<uses-permission android:name="android.permission.INTERNET" />
The main content includes:
- Basic usage
- Zooming
- Building web pages to support different screen densities
- HTML5 video support
- Full-screen support
- HTML5 geolocation API
- Layout size
- Collecting error data
Basic usage#
By default, WebView does not enable JavaScript and ignores web page errors. This is useful if you only want to display HTML on the UI without any user interaction. If you need a full browser functionality, you should use the appropriate Intent to launch the browser instead of using WebView. You can use the following code to launch the system browser:
Uri uri = Uri.parse("https://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
There are two main ways to use WebView: creating and using it directly in the onCreate() method of an Activity, or including it in a layout file. Here are examples of both methods:
Creating WebView directly in code#
WebView webview = new WebView(this);
// Set the entire activity window as the WebView's display area, or you can place it in a specific layout
setContentView(webview);
Using WebView in a layout file#
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
So how do we load a web page? How do we load a local web page? And how do we load a HTML fragment? There are two common methods for loading web content:
Loading a complete web page#
Here are examples of loading the homepages of Baidu, CSDN, and Tencent. When loading the Baidu homepage, you need to set the following properties to display the content correctly:
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl("https://www.baidu.com");
When loading the CSDN homepage, you need to set the following properties to directly load the content:
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://blog.csdn.net");
When loading the Tencent homepage, you can directly load the content:
webView.loadUrl("http://www.qq.com");
Please note that the results may vary depending on the testing environment.
Loading a local HTML file#
When loading an HTML file from the SD card, you need to request the permission to access the SD card in the AndroidManifest.xml file, as shown below:
// Load an HTML file from the assets directory
webView.loadUrl("file:///android_asset/mine.html");
// Load an HTML file from the SD card
webView.loadUrl("file:///"+Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"mine.html");
Loading an HTML fragment#
When loading an HTML fragment, you need to set the character set to prevent garbled characters, as shown below:
// Load an HTML fragment and set the character set to prevent garbled characters
webView.loadData(Util.getHtmlData(),"text/html; charset=UTF-8",null);
There are several aspects to consider when setting up and handling WebView:
- Create and set a WebChromeClient to assist WebView in handling JavaScript dialogs, website titles, loading progress, etc.
- Create and set a WebViewClient to provide various event callbacks.
- Use the WebSetting object to set various properties of WebView, such as enabling JavaScript, setting WebView cache, font size, etc.
- Interact between JS and Java, such as using the addJavascriptInterface(Object, String) method to inject Java objects into the WebView's JavaScript context, allowing them to be accessed by JavaScript in the page.
Zooming#
Starting from Android 1.5, you can enable built-in zooming by calling the following method:
WebSettings.setBuiltInZoomControls(boolean)
Note: Enabling built-in zooming while setting WebView's width and height to wrap_content may cause undefined behavior. It is recommended to avoid this situation.
Building web pages to support different screen densities#
Screen density is based on screen resolution. Low-density screens have fewer pixels per inch, while high-density screens have more pixels per inch. Screen density is important because UI elements defined in pixels will appear larger on low-density screens and smaller on high-density screens. To facilitate this, Android converts actual screen densities into three general densities: high, medium, and low.
By default, WebView scales web pages to match the default appearance on medium-density screens. This means that on high-density screens, the content is scaled to 1.5 times (smaller pixels), and on low-density screens, the content is scaled to 0.75 times (larger pixels). Starting from Android 2.0, WebView supports DOM, CSS, and meta tags to help web developers adapt to different screen densities.
Here are some explanations for handling different screen densities:
- Use the window.devicePixelRatio property to specify the default scaling factor of the current device, which represents the ratio of physical pixels to device-independent pixels (dips). If the value of window.devicePixelRatio is 1, the device is considered a medium-density (mdpi) device and the default scaling is not applied. If the value is 1.5, the device is considered a high-density (hdpi) device and the content is scaled by 1.5 times. If the value is 0.75, the device is considered a low-density (ldpi) device and the content is scaled by 0.75 times. The formula is as follows:
- Use the -webkit-device-pixel-ratio CSS media query to specify the screen density for which the style sheet is applicable. The values can be 0.75, 1, or 1.5, indicating that the style sheet is applicable to low-density, medium-density, or high-density screens, respectively. The following example shows that the hdpi.css style sheet is only applicable to screens with a pixel density ratio of 1.5, which means it is suitable for high-density screens.
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />
HTML5 video support#
To support HTML videos in your application, you need to enable hardware acceleration.
Please refer to the following link for information about hardware acceleration: Android Hardware Acceleration
Full-screen support#
To support full-screen display of videos or other HTML content, you need to set a WebChromeClient and implement the onShowCustomView(View, WebChromeClient.CustomViewCallback) and onHideCustomView() methods:
onShowCustomView#
Notifies the application that the current page has entered full-screen mode, and the application should display the web content, video, and other HTML content in full-screen mode.
/**
* @param view The view to be displayed.
* @param callback The callback to be called when the current page exits
* full screen mode.
*/
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {};
onHideCustomView#
Notifies the application that the current page has exited full-screen mode, and the application should hide the custom view.
public void onHideCustomView() {}
If either of these methods is not implemented, the web page cannot enter full-screen mode. You can also implement getVideoLoadingProgressView() to customize the view displayed during video buffering.
public View getVideoLoadingProgressView() {
return null;
}
HTML5 geolocation API#
For Android N and devices with API level > M, the geolocation API only supports HTTPS. If the application requests the geolocation API in a non-HTTPS manner, the onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback) method will be denied.
Layout size#
It is recommended to set the height of WebView to a fixed value or MATCH_PARENT instead of using WRAP_CONTENT. If WebView's height is set to MATCH_PARENT and its parent layout's height is set to WRAP_CONTENT, it may cause inconsistent sizes.
Setting WebView's height to WRAP_CONTENT will result in the following behaviors:
- The height of the HTML is set to a fixed value, which means that the sizes of elements relative to the HTML BODY height may be incorrect.
- For devices running Android 4.4 or earlier, the meta tag will be ignored to ensure backward compatibility.
WRAP_CONTENT for layout width is not supported. If you use this width, WebView will attempt to use the width of its parent layout.
Collecting error data#
If the user agrees, some diagnostic data from WebView will be anonymously uploaded to Google to help improve WebView. This data is collected for every initialized WebView application. If you want to disable this feature, you can add the following setting in the manifest file:
<meta-data
android:name="android.webkit.WebView.MetricsOptOut"
android:value="true" />
Reference link: WebView Official Documentation