您的当前位置:首页正文

[翻译] 对Android官方文档说爱你 -- WebView篇

来源:华佗小知识
前言

很多人都说官方文档是最好Android学习资料,但是由于种种原因:或无法科学上网(你懂的),或语言障碍,总是不能对它say love。本人是一名刚毕业的程序媛,英语六级水平,趁着大学英语还没有退化,本着大家互相学习的原则,尽可能多的翻译一些官方介绍,如果有错误请大家踊跃指出,谢谢。


WebView.png

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.

这是一个用于展示网页的视图控件。在这个类的基础上,你可以(译者注:调用)滚动你自带的web浏览器,也可以在Activity上简单地展示一些线上的内容。它使用WebKit渲染引擎显示web页面,并且包含了一些方法:通过历史记录向前或向后导航,放大和缩小,执行文本搜索等。

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:

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

注意,为了让你的Activity能够访问互联网并且能够加载Web页面到WebView中,你必须在你的Android清单文件中添加网络访问权限:

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

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:

Uri uri = 
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);  

默认情况下,WebView没有提供的类似浏览器部件(译者注:的设置),不支持JavaScript并且web页面报错也被忽略了。如果你的目标只是显示一些HTML 来作为你界面的一部分,这可能不错;除了阅读之外,用户不需要与网页交互,web页面也不需要与用户进行交互。如果你真的想要一个成熟的web浏览器,那么你可能需要通过一个URL意图调用浏览器应用程序,而不是使用WebView。例子:

Uri uri = 
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);  
WebView webview = new WebView(this); 
setContentView(webview);

为了在你自己的Activity中使用WebView,需要在布局文件中添加一个< WebView >标签,或通过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("http://slashdot.org/"); 

// 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 forloadData() and loadDataWithBaseURL() for more info. 

然后加载所需的网页:

// 最简单的运用:注意,在这种情况下,如果在加载的页面出现错
// 误,这个异常不会被抛出(代码如下)
webview.loadUrl("http://slashdot.org/"); 

// 或者,你也可以通过HTML字符串来加载页面 
String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 
webview.loadData(summary, "text/html", null); 
// ... 但是要注意HTML的一些使用限制。
// 请查看loadData()和 loadDataWithBaseURL() 的Java文档去获取更多的信息。

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

  • Creating and setting a 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 ).
  • Creating and setting a 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()](, java.lang.String))).
  • Modifying the , such as enabling JavaScript with .
  • Injecting Java objects into the WebView using the [addJavascriptInterface(Object, String)](, java.lang.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.

WebView有多种定制点,你可以添加你自己的行为。分别是:

  • 创建和设置子类。这个类将在浏览器用户界面受到影响时被调用* (译者注:主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等) *,比如:界面更新时或在这里发送JavaScript alert时(参见 )。
  • 创建和设置 子类。这个类将在内容呈现受到影响时被调用*(译者注:主要处理各种通知、请求事件) *,比如,错误提交或表单提交时。你也可以在这里拦截URL加载(通过shouldOverrideUrlLoading())。
  • 修改比如通过设置JavaScript可用。
  • 通过[addJavascriptInterface(Object, String)](, java.lang.String))方法给WebView注入Java对象。这个方法允许您将Java对象注入到一个页面的JavaScript上下文,这样他们就可以在页面上通过JavaScript访问该对象* (译者注:即通过这个方法可以实现JS调用Java) *。
    <p>

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();  
   }
 }); 

 

下面是一个较为复杂的例子,展示了错误处理、设置和进度提示:

// 我们在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) {     
    //  Activity和WebView的进度条以不同的方式计量进度
    //  进度条会在到达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();  
   }
 }); 

 

<p>

Zoom

缩放

Cookie and window management

Cookie和窗口管理器

For obvious security reasons, your application has its own cache, cookie store etc.—it does not share the Browser application's data.

出于明显的安全因素,你的应用程序有自己的缓存,如cookie store等。它不共享浏览器应用的数据。

默认情况下,HTML的打开新窗口的请求将被忽略。新窗口将通过JavaScript打开,或通过链接上的目标属性打开。你可以定制WebChromeClient的行为,使它开放多个窗口,也可以使他们成为具备任何你想要的行为。

Building web pages to support different screen densities

构建web页面来支持不同的屏幕密度

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.

设备的屏幕密度由屏幕分辨率决定。低密度屏幕在每英寸屏幕上有很少的可用像素点,高密度屏幕在每英寸屏幕上通常有更多的可用像素点。屏幕的密度是很重要的,因为,在其他条件相同的情况下,一个用户界面元素(如按钮)的高度和宽度的定义是依据屏幕像素决定的,它会在低密度屏幕上显示的更大,在高密度屏幕上显示的更小。为简单起见,Android将所有实际屏幕密度分缩减为三个广义密度:高,中,低。

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 ofwindow.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.devicePixelRatioDOM属性。这个属性的值明确说明了用在当前设备上的默认比例因子。例如,如果window.devicePixelRatio的值是“1.0”,那么该设备被认为是中等密度(mdpi)设备并且默认缩放不应用于web页面;如果值是“1.5”,那么该设备被认为是高密度(hdpi)设备并且页面内容是按比例拉伸到1.5倍;如果值是“0.75”,那么该设备被认为是低密度(hdpi)设备并且页面内容是按比例拉伸到0.75倍。

  • 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:

<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.

  • -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" />

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.

为了让你的应用支持内联HTML视频你需要选择硬件加速。

Full screen support

全屏支持

HTML5 Geolocation API support

HTML5地理定位API支持

Layout size

布局尺寸

  • 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的高度可能不正确。

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:

 <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.

在用户同意后,WebView可能会将匿名诊断数据上传到Google。这些数据可以帮助Google优化WebView。google将从每个实例化WebView的应用程序中收集数据,每个应用程序都可以通过在清单中做上以下标记来取消这一特性:

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

只有当用户已经同意,并且给定应用程序没有选择退出时,才可以上传数据。


本篇结束啦~~
如果有错误请告诉我,我会及时修改;
如果感觉还不错的话,请给我一个喜欢以表鼓励啦(__)