WebView basic use and related features

WebView is a display component web content can be displayed some online content on the network and can be used as the contents of the Web browser scroll, which uses WebKit as a rendering engine to display web pages, which include zoom, perform a text search, etc. before and after method of navigation.

Note : If you want to display the contents of web pages online in WebView, you need to add a network permission in AndroidManifest.xml file, refer to the following:

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

Basic Usage

WebView is not enabled by default JavaScript, error pages will also be ignored, if only to display some HTML on the UI, this will be very good, before the user interacts with the user do not need to read the page does not need to interact with the user, if you need a full browser, you need to call the appropriate Intent to launch the browser to perform certain actions, rather than using WebView to display, call the system browser to use the following code:

Uri uri = Uri.parse("https://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
 

WebView mainly used in two ways, like in the Activity onCreate () method used to create or directly incorporated in the layout file, refer to the following:

1. Create a WebView directly from your code

WebView webview = new WebView(this);
//这里将整个 Activity 窗口作为 WebView 的显示界面,也可单独放在某个布局中
setContentView(webview);


2. Use WebView in the layout file

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

So how do we load a page, if the page is local and how to load it, and how to load an HTML fragment it, loading method commonly used for two main, as follows:

1. Load a full page

Here tested using Baidu Home, CSDN Home, Home Tencent test, test Baidu home page, you need to set the following properties page content to be displayed correctly, if not setting appears in black and white:

webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl("https://www.baidu.com");

CSDN home test, you will be prompted to open the application with a browser to open the page, set the following properties in order to load the page content directly:

webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://blog.csdn.net");

Home content can be loaded directly test Tencent Home:

webView.loadUrl("http://www.qq.com");

Test environment may be different, the result is not the same.

2. load a local HTML file

Where to apply for access to the SD card Manifest.permission.WRITE_EXTERNAL_STORAGE when loading HTML file on the SD card, refer to the following:

//加载 assets 目录下的 HTML 文件
webView.loadUrl("file:///android_asset/mine.html");
//加载 SD 卡上的 HTML 文件
webView.loadUrl("file:///"+Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+"mine.html");

3. Load HTML snippet

When loading HTML fragment, to set the character set, otherwise it will be garbled, refer to the following:

//加载 HTML 片段,设置字符集防止乱码出现
webView.loadData(Util.getHtmlData(),"text/html; charset=UTF-8",null);

WebView interface setup and processing mainly in the following areas:

  1. Create and set WebChromeClient, mainly secondary WebView to handle JavaScript dialog boxes, web site title, loading progress and so on;
  2. Create and set WebViewClient, mainly to provide a variety of events such as callback;
  3. WebSetting objects may be provided by a variety of WebView related attributes, such as support JavaScript, WebView cache set, font size, and the like;
  4. Java and JS call each other, such as the use addJavascriptInterface (Object, String) method of Java objects injected WebView. This method allows you to inject Java objects to JavaScript in the context of the page, so you can access them through the pages JavaScript.

Scaling

Android supports call the following method to enable the built-in zoom after 1.5:

WebSettings.setBuiltInZoomControls(boolean)

Note : Setting a built-in zoom, width and height of WebView is wrap_content, will lead to undefined behavior, it should be avoided during use.

Build Web pages to support different screen densities

Screen density is based on screen resolution, low-density screen pixels per inch less available, high-density screens available more pixels per inch, the screen density is more important, because other factors being the same, based on the pixel definition UI elements displayed on a large screen low-density, small display on the screen higher density screen; Android screen for convenience in terms of the actual density of more extensive screen density: high, medium and low.

By default, the WebView scaled web page to the default appearance on the screen size and the density of the drawn match, so the screen is suitable for high-density 1.5-fold scale (smaller pixel) on the screen is suitable for low-density 0.75 times zoom (pixels larger); starting from Android 2.0 WebView support for DOM, CSS and meta tags to help Web developers to adapt the target screen based on different screen densities.

Here are some instructions to handle different screen densities:

  1. Window.devicePixelRatio using default attribute specifies the current device scaling factor, also refers to the individual pixels on the device physical pixels and devices (device-independent pixels (dips)) ratio, if window.devicePixelRatio is 1, then the device is considered to be density (mdpi) apparatus, and the default does not apply scaling page if window.devicePixelRatio value 1.5 times, then the device is considered to be a high-density device (hdpi), scaled to 1.5 times the content of the page; if window.devicePixelRatio 0.75, then the device is considered to be low-density device (ldpi), the content is scaled to 0.75 times the original, formulated as follows:

window.devicePixelRatio(dpr) = physical pixel / dips(css pixel)}

physical pixel = dips *  density / 160} (Android)
  1. Use -webkit-device-pixel-ratio CSS media query screen to specify style sheet density, which value should be 0.75, 1, 1.5, respectively, which indicate a stylesheet is applied to a low density, medium density, high density screen device , as the following statement applies only to show hdpi.css screen pixel density ratio of 1.5 for the screen of the device, which is suitable for high-density screen device.
 <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />

HTML5 video support

If support HTML video in your application, you need to enable hardware acceleration.

About hardware acceleration, please refer to: Android hardware acceleration

Full screen support

In order to support full-screen, such as video or other HTML content, you need to set a WebChromeClient and implement two methods onShowCustomView (View, WebChromeClient.CustomViewCallback) and onHideCustomView ():

1. onShowCustomView

Inform the application of the current page to enter full-screen mode, the application in full-screen mode includes Web content, videos, and other content in HTML.

/**
 * @param view 显示的View.
 * @param callback 调用当前页退出当前页
 * full screen mode.
 */
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {};

2. onHideCustomView

Inform the application of the current page exit full-screen mode, the application must hide the custom of View.

public void onHideCustomView() {}

If any one of these methods is not achieved, then the Web page corresponding to the page can not enter full-screen mode can be achieved getVideoLoadingProgressView (defined from a view of the video buffer to be displayed).

 public View getVideoLoadingProgressView() {
        return null;
}

HTML5 Geolocation API

For Android N and the API level> M devices, HTTPs location API supports only manner, if applied in a manner non-HTTPS request location API onGeolocationPermissionsShowPrompt (String, GeolocationPermissions.Callback) method call will be rejected.

Layout size

WebView recommended height is set to a fixed value or is not recommended match_parent WRAP_CONTENT, if the height WebView uses MATCH_PARENT, its parent WRAP_CONTENT highly practical layout result in inconsistent size staircase.

The height of the WebView is set to WRAP_CONTENT behavior will appear as follows:

  1. HTML height is set to become a fixed value, which means that relative to the size of the height of the HTML BODY element may be incorrect;
  2. For applications where the device is Android 4.4 and earlier SDk, meta tags will be ignored in order to ensure backward compatibility;

It does not support the use of layout width WRAP_CONTENT. If such width, WebView will try to use the width of its parent layout.

Collect data on error

If the user agrees, some diagnostic data WebView will anonymously uploaded to Google, these data will help Google improve WebView, each initialized WebView application will collect these data, if you want to disable the feature in the list of documents required in the following settings:

 <meta-data 
    android:name="android.webkit.WebView.MetricsOptOut"
    android:value="true" />

Reference links: WebView official website

If you feel that they have to help, you can focus the public number: jzman-Blog , with the exchange of learning.

Guess you like

Origin www.cnblogs.com/jzmanu/p/12585309.html