webview最全面详解(一)了解官方文档

简单介绍

WebView是手机中内置了一款高性能 webkit 内核浏览器,在 SDK 中封装的一个组件。没有提供地址栏和导航栏,WebView只是单纯的展示一个网页界面。在开发中经常都会用到。

显示和渲染Web页面
直接使用html文件(网络上或本地assets中)作布局
可和JavaScript交互调用
WebView控件功能强大,除了具有一般View的属性和设置外,还可以对url请求、页面加载、渲染、页面交互进行强大的处理。

本文翻译官方文档认识和了解webview。

翻译

官方文档 (自备梯子)

这里写图片描述

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

一个用来展示网页的view控件,在这个类的基础上,你可以在你的activity中使用系统自带浏览器或者简单的展示一些在线的内容。

Note that, in order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file:

请注意,为了让您的Activity能访问网络并在WebView中加载网页,您必须将INTERNET权限添加到您的Android Manifest文件中:

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

This must be a child of the element.
For more information, read Building Web Apps in WebView.

这条必须作为 元素的子标签。
更多信息请阅读用WebView构建 Web应用程序

Basic usage

By default, a WebView provides no browser-like widgets, does not enable JavaScript and web page errors are ignored. If your goal is only to display some HTML as a part of your UI, this is probably fine; the user won’t need to interact with the web page beyond reading it, and the web page won’t need to interact with the user. If you actually want a full-blown web browser, then you probably want to invoke the Browser application with a URL Intent rather than show it with a WebView. For example:

默认情况下,webview并不提供类似浏览器的不见,不支持JavaScript 并且忽略网页错误。如果你的目的是仅仅显示一些HTML作为你的UI的一部分,那可能不错,用户阅读网页而不需要与之交互,网页也不需要和用户交互。
如果你真的想要一个完整的Web浏览器,那你可能需要通过一个URL intent调用浏览器应用程序而不是在WebView中显示它,
例如:

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

See Intent for more information.

To provide a WebView in your own Activity, include a in your layout, or set the entire Activity window as a WebView during onCreate():
请参阅意图获取更多信息。
要在你的activity中支持webview,需要在layout中添加标签,或者在 onCreate()方法中将整个activity窗口设置为一个webview。

 WebView webview = new WebView(this);
 setContentView(webview);

Then load the desired web page:

然后加载所需网页

 // Simplest usage: note that an exception will NOT be thrown
 // if there is an error loading this page (see below).
 // 最简单的应用:注意在这种情况下,如果在加载的页面出现错
// 误,这个异常不会被抛出(如下)
 webview.loadUrl("https://example.com/");

 // OR, you can also load from an HTML string:
 //而或,你也可以加载HTML字符串

 String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview.loadData(summary, "text/html", null);

 // ... although note that there are restrictions on what this HTML can do.
 // See loadData(String, String, String) and loadDataWithBaseURL(String, String, String, String, String) for more info.
 // Also see loadData(String, String, String) for information on encoding special characters.
 当然,要注意的是加载HTML是有限制的
 请查阅loadData(String, String, String)和loadDataWithBaseURL(String, String, String, String, String)文档获取更多信息。
 有关编码特殊字符的信息,另请参阅loadData(StringStringString)。

A WebView has several customization points where you can add your own behavior. These are:

Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. This method allows you to inject Java objects into a page’s JavaScript context, so that they can be accessed by JavaScript in the page.
Here’s a more complicated example, showing error handling, settings, and progress notification:

webview有一些可以自定义的地方,你可以自定义自己的方法。这些分别是:

创建和设置一个WebChromeClient WebChromeClient 类。当某些可能影响浏览器用户界面的事件发生时会调用此类,例如,发送进度更新和JavaScript弹出alert的时候(请参阅调试任务)。
(译者注:WebChromeClient是辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等 )

创建和设置一个WebViewClient 类,当影响内容呈现的事情发生时,它会被调用,例如提交错误或表单。 你也可以在这里拦截URL加载(通过 shouldOverrideUrlLoading()]
(译者注:WebViewClient就是帮助WebView处理各种通知、请求事件的)

 // Let's display the progress in the activity title bar, like the
 // browser app does.
 //让我们像浏览器程序一样在activity标题栏展示加载进度
 getWindow().requestFeature(Window.FEATURE_PROGRESS);

 webview.getSettings().setJavaScriptEnabled(true);

 final Activity activity = this;
 webview.setWebChromeClient(new WebChromeClient() {
   public void onProgressChanged(WebView view, int progress) {
     // Activities and WebViews measure progress with different scales.
     // The progress meter will automatically disappear when we reach 100%
     //Activities 和WebViews以不同比例衡量进度。进度条会在我们达到100%时自动消失
     activity.setProgress(progress * 1000);
   }
 });
 webview.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
   }
 });

 webview.loadUrl("https://developer.android.com/");

Zoom

缩放

To enable the built-in zoom, set WebSettings.setBuiltInZoomControls(boolean) (introduced in API level CUPCAKE).

Note: Using zoom if either the height or width is set to WRAP_CONTENT may lead to undefined behavior and should be avoided.

要启用内置缩放,请设置 WebSettings.setBuiltInZoomControls(boolean) (在 CUPCAKE的API有介绍)。
注意:如果高度或宽度设置为WRAP_CONTENT,则使用缩放可能会导致未定义的行为,应该避免。

Cookie和窗口管理

For obvious security reasons, your application has its own cache, cookie store etc.—it does not share the Browser application’s data.
出于安全的考虑,你的应用有自己的缓存,cookie存储——它不与浏览器应用共享数据。

By default, requests by the HTML to open new windows are ignored. This is true whether they be opened by JavaScript or by the target attribute on a link. You can customize your WebChromeClient to provide your own behavior for opening multiple windows, and render them in whatever manner you want.

默认情况下,HTML发出的打开新窗口的请求会被忽略。 无论它们是由JavaScript打开还是由链接上的目标属性打开,都是如此。 您可以自定义您的WebChromeClient以规定你自己的行为以打开多个窗口,并以你想要的任何方式呈现它们。

The standard behavior for an Activity is to be destroyed and recreated when the device orientation or any other configuration changes. This will cause the WebView to reload the current page. If you don’t want that, you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone. It’ll automatically re-orient itself as appropriate. Read Handling Runtime Changes for more information about how to handle configuration changes during runtime.

对于activity的标准行为来说,当设备方向或任何其他配置更改时,其都将被销毁并重建。这将导致webview去重载当前界面,如果你不希望如此,你可以设置你的Activity来处理orientation和keyboardHidden变化,不用理会WebView。 它会自动适当地重新定位自己。 阅读 Handling Runtime Changes 来获取有关如何处理运行时配置更改的更多信息。


Building web pages to support different screen densities

构建网页适配不同屏幕密度

The screen density of a device is based on the screen resolution. A screen with low density has fewer available pixels per inch, where a screen with high density has more — sometimes significantly more — pixels per inch. The density of a screen is important because, other things being equal, a UI element (such as a button) whose height and width are defined in terms of screen pixels will appear larger on the lower density screen and smaller on the higher density screen. For simplicity, Android collapses all actual screen densities into three generalized densities: high, medium, and low.

一个设备的屏幕密度是基于屏幕分辨率。低密度的屏幕每英寸有较少的可用像素点,高密度的通常很明显的屏幕每英寸有较多的像素点。屏幕密度是很重要的,在其他的条件相同下,一个用屏幕像素定义和设置高度和宽度的UI元素(例如一个按钮),在低密度的屏幕显示较大,而在高密度的屏幕显示较小。为了简单,Android 将所有屏幕密度分为三个广义的密度:高,中,低。

By default, WebView scales a web page so that it is drawn at a size that matches the default appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels are bigger). Starting with API level ECLAIR, WebView supports DOM, CSS, and meta tag features to help you (as a web developer) target screens with different screen densities.

默认情况下,WebView会缩放网页,以便在中等密度屏幕上以与默认外观相匹配的尺寸绘制网页。 因此,它在高密度屏幕上应用1.5倍缩放(因为其像素点较小),在低密度屏幕上缩放0.75倍(因为其像素点较大)。 从API为ECLAIR开始,WebView支持DOM,CSS和meta tag标签功能,以帮助你(Web开发人员)适配不同屏幕密度的屏幕。

Here’s a summary of the features you can use to handle different screen densities:

以下是可用于处理不同屏幕密度的功能摘要:

The window.devicePixelRatio DOM property. The value of this property specifies the default scaling factor used for the current device. For example, if the value of window.devicePixelRatio is “1.0”, then the device is considered a medium density (mdpi) device and default scaling is not applied to the web page; if the value is “1.5”, then the device is considered a high density device (hdpi) and the page content is scaled 1.5x; if the value is “0.75”, then the device is considered a low density device (ldpi) and the content is scaled 0.75x.

window.devicePixelRatio DOM属性。 此属性的值指定用于当前设备的默认比例因子。 例如,如果window.devicePixelRatio的值为“1.0”,则该设备被视为中等密度(mdpi)设备,并且默认缩放不会应用于网页; 如果该值是“1.5”,则该设备被认为是高密度设备(hdpi),并且页面内容被缩放为1.5倍; 如果该值为“0.75”,则该设备被认为是低密度设备(ldpi),并且该内容被缩放为0.75x。

The -webkit-device-pixel-ratio CSS media query. Use this to specify the screen densities for which this style sheet is to be used. The corresponding value should be either “0.75”, “1”, or “1.5”, to indicate that the styles are for devices with low density, medium density, or high density screens, respectively. For example:

The-webkit-device-pixel-ratio CSS查询。 使用此选项指定要使用此样式表的屏幕密度。 相应的值应该是“0.75”,“1”或“1.5”,以表明这些样式分别适用于低密度,中等密度或高密度屏幕的设备。 例如:

 <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />

The hdpi.css stylesheet is only used for devices with a screen pixel ration of 1.5, which is the high density pixel ratio.

hdpi.css样式表仅用于屏幕像素比为1.5的设备,即高密度屏幕。

HTML5 Video support

HTML5 视频支持

In order to support inline HTML5 video in your application you need to have hardware acceleration turned on.

为了在你的应用程序中支持嵌入式HTML5视频,你需要打开硬件加速。

Full screen support

全屏支持

In order to support full screen — for video or other HTML content — you need to set a WebChromeClient and implement both onShowCustomView(View, WebChromeClient.CustomViewCallback) and onHideCustomView(). If the implementation of either of these two methods is missing then the web contents will not be allowed to enter full screen. Optionally you can implement getVideoLoadingProgressView() to customize the View displayed whilst a video is loading.

为了支持全屏 - 播放视频或展示其他的HTML内容 - 你需要设置WebChromeClient并实现onShowCustomView(View,WebChromeClient.CustomViewCallback)和onHideCustomView()。 如果缺少这两种方法中的任何一种,网页内容将不被允许进入全屏模式。 此外,你可以通过实现getVideoLoadingProgressView()方法,来自定义加载视频时显示的视图。

HTML5 Geolocation API support

HTML5 地理位置API 支持

For applications targeting Android N and later releases (API level > M) the geolocation api is only supported on secure origins such as https. For such applications requests to geolocation api on non-secure origins are automatically denied without invoking the corresponding onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback) method.

对于面向Android N及更高版本(API级别> M)的应用程序,地理位置api仅在安全来源(如https)的请求受支持。 对于此类应用程序,在不调用相应的onGeolocationPermissionsShowPrompt(String,GeolocationPermissions.Callback)方法的情况下,会自动拒绝在非安全来源上对地理位置api的请求。

Layout size

布局尺寸

It is recommended to set the WebView layout height to a fixed value or to MATCH_PARENT instead of using WRAP_CONTENT. When using MATCH_PARENT for the height none of the WebView’s parents should use a WRAP_CONTENT layout height since that could result in incorrect sizing of the views.

推荐设置webview的layout height设置为固定值或者设置为MATCH_PARENT而不是WRAP_CONTENT。当高度使用MATCH_PARENT时,WebView的父级都不应使用WRAP_CONTENT布局高度,因为这可能会导致视图大小不正确。

Setting the WebView’s height to WRAP_CONTENT enables the following behaviors:

设置webview的高度为WRAP_CONTENT 可能将会导致以下行为:

The HTML body layout height is set to a fixed value. This means that elements with a height relative to the HTML body may not be sized correctly.
For applications targeting KITKAT and earlier SDKs the HTML viewport meta tag will be ignored in order to preserve backwards compatibility.

HTML的body高度设置为固定值。 这意味着和HTML body高度有关的元素的尺寸可能不正确。
对于面向KITKAT和更早SDK的应用程序,为了保持向后兼容性,HTML视图元标签将被忽略。

Using a layout width of WRAP_CONTENT is not supported. If such a width is used the WebView will attempt to use the width of the parent instead.

不支持使用WRAP_CONTENT的布局宽度。 如果使用这样的宽度,WebView将尝试使用父宽度。

Metrics

数据收集

WebView may upload anonymous diagnostic data to Google when the user has consented. This data helps Google improve WebView. Data is collected on a per-app basis for each app which has instantiated a WebView. An individual app can opt out of this feature by putting the following tag in its manifest’s element:

当用户同意时,WebView可能会将匿名诊断数据上传到Google。 这些数据有助于Google改进WebView。 实例化WebView的每个应用程序,都会被收集数据。 每个应用程序都可以通过在清单的元素中加入以下标签来取消此功能:

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

Data will only be uploaded for a given app if the user has consented AND the app has not opted out.

只有在用户同意并且应用程序未退出的情况下,数据才会上传。

Safe Browsing

安全浏览

With Safe Browsing, WebView will block malicious URLs and present a warning UI to the user to allow them to navigate back safely or proceed to the malicious page.

借助安全浏览功能,WebView将阻止恶意网址并向用户显示警告用户界面,允许他们安全地导航返回或者是进入恶意页面。

Safe Browsing is enabled by default on devices which support it. If your app needs to disable Safe Browsing for all WebViews, it can do so in the manifest’s element:

安全浏览默认情况下在支持它的设备上启用。 如果您的应用需要禁用所有WebView的安全浏览,则可以在manifest的元素中执行此操作:

 <manifest>
     <application>
         ...
         <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
             android:value="false" />
     </application>
 </manifest>

Otherwise, see setSafeBrowsingEnabled(boolean).

更多的请参阅setSafeBrowsingEnabled(boolean).

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值