WebView 文档 翻译


WebView 文档

public class android.webkit.WebView extends AbsoluteLayout 
           implements ViewTreeObserver.OnGlobalFocusChangeListener, ViewGroup.OnHierarchyChangeListener
java.lang.Object
   ↳	android.view.View
 	   ↳	android.view.ViewGroup
 	 	   ↳	android.widget.AbsoluteLayout
 	 	 	   ↳	android.webkit.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.
显示网页的视图。 这个类是您可以滚动自己的网络浏览器,或只是在您的Activity中显示一些在线内容的基础。 它使用WebKit渲染引擎来显示网页,并且包括通过历史记录,放大和缩小,执行文本搜索等进行前进后退导航的方法。

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 访问Internet并在WebView中加载网页,您必须将INTERNET权限添加到AndroidManifest文件中

For more information, read Building Web Apps in WebView.

1、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来显示。 例如:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidi.com")));

To provide a WebView in your own Activity, include a <WebView> in your layout, or set the entire Activity window as a WebView during onCreate():
setContentView(new WebView(this));

Then load the desired web page:
// Simplest usage: note that an exception will NOT be thrown if there is an error loading this page
webview.loadUrl("https://example.com/");

// OR, you can also load from an HTML string:
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 the JavaDocs for loadData() and loadDataWithBaseURL() for more info.

A WebView has several customization points where you can add your own behavior. These are:
WebView有几个自定义点,您可以添加自己的行为。 这些是:
  • 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.
    创建和设置WebChromeClient子类。 当可能影响浏览器UI的事情发生时,调用此类,例如,进度更新和JavaScript警报在此发送。
  • 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()).
    创建和设置WebViewClient子类。 当事情发生时影响内容的呈现,例如错误或表单提交将被调用。 你也可以在这里拦截URL加载。
  • Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
    修改WebSettings,例如使用setJavaScriptEnabled启用JavaScript。
  • 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.
    使用addJavascriptInterface方法将Java对象注入WebView。 此方法允许您将Java对象注入到页面的JavaScript上下文中,以便可以通过页面中的JavaScript访问它们。

Here's a more complicated example, showing error handling, settings, and progress notification:
这是一个更复杂的例子,显示错误处理,设置和进度通知:
// Let's display the progress in the activity title bar, like the browser app does.
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%
    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/");

2、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.
注意:如果高度或宽度设置为WRAP_CONTENT,使用缩放可能会导致未定义的行为,应该避免。

3、Cookie and window management

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打开还是链接上的target属性,都是如此。 您可以自定义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来处理方向和键盘的隐藏变化,然后就不需要再管WebView了。 它将自动 适当的 重新定位自己。 有关如何在运行时处理配置更改的更多信息,请阅读"处理运行时更改"。

4、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和元标记功能,可帮助您(作为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)设备,并且默认缩放不应用于网页;
  • 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:
    -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的设备,这是高密度像素比。

5、HTML5 Video support

In order to support inline HTML5 video in your application you need to have hardware acceleration turned on.
为了在应用程序中支持内置HTML5视频,您需要启用硬件加速。

6、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和onHideCustomView。 如果这两种方法中的任何一种的实现丢失,则Web内容将不被允许进入全屏。 或者,您可以实现getVideoLoadingProgressView来自定义视频加载时显示的视图。

7、HTML5 Geolocation地理位置 API support

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。 对于这样的应用程序,对非安全起始地址的api的请求将自动被拒绝,而不会调用相应的onGeolocationPermissionsShowPrompt方法。

8、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布局高度设置为固定值或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.
    HTML主体布局高度会被设置为固定值。 这意味着,相对于"HTML主体的"的元素的高度可能不正确。
  • For applications targeting KITKAT and earlier SDKs the HTML viewport meta tag will be ignored in order to preserve保持、保留 backwards compatibility.
    针对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会尝试使用父布局的宽度来代替。

9、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:
当用户同意后,WebView可能回将匿名诊断数据上传到Google。 这些数据有助于Google改进WebView。 针对已实例化WebView的每个应用程序,每个应用程序都会收集数据。 单个应用可以通过在其清单中放置以下标签来选择停用此功能:
<meta-data
    android:name="android.webkit.WebView.MetricsOptOut"
    android:value="true"/>
Data will only be uploaded for a given app if the user has consented AND the app has not opted out.
对于 给定的应用, 数据将只会在 用户同意并且该应用没有选择退出时 被上传。

2017-8-17




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值