Android 翻译:WebView Class Overview

WebView Class Overview

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.

WebView是用来显示网页的。它是你开发自己的web浏览器的基础,也可以用来在Activity中只是显示一些在线内容。它使用WebKit作为底层引擎,包括向前先后的导航,缩放,文字搜索等等。

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

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

This must be a child of the element.

See the Web View tutorial.

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、忽略网页错误。如果你的目标只是在UI中展示HTML是很好的;用户不必和网页交互操作,只是读内容。如果你想要一个全功能的web浏览器,你需要使用URL intent启动一个浏览器,而不是在WebView中显示。

 Uri uri = Uri.parse("http://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():

在layout中包括WebView 或 设置整个window只有一个WebView 在onCreate()中:

 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 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 (see Debugging Tasks).
  • 创建和设置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,例如:让JavaScript可用--setJavaScriptEnabled().
  • Adding JavaScript-to-Java interfaces with the addJavascriptInterface(Object, String) method. This lets you bind Java objects into the WebView so they can be controlled from the web pages JavaScript.
  • 增加JavaScript-to-Java接口addJavascriptInterface(Object,String)。可以将java对象绑定到WebView,这样对象可以被网页的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("http://slashdot.org/");
 

Cookie and window management

Cookie和window管理

For obvious security reasons, your application has its own cache, cookie store etc.—it does not share the Browser application's data. Cookies are managed on a separate thread, so operations like index building don't block the UI thread. Follow the instructions in CookieSyncManager if you want to use cookies in your application.

由于安全的原因,你的应用有自己的缓存和cookie存储。Cookies在一个单独的线程中管理,像建立索引这样的操作不会阻塞UI线程。如果想使用cookies,可以查看CookieSyncManager 。

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 yourWebChromeClient to provide your own behaviour 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 改变。阅读 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.

屏幕密度建立在屏幕分辨率上。低密度在每英寸上有较少的可用像素,高分辨率有更多像素--每英寸像素数PPI。一个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 5 (Android 2.0), 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 Leve 5(Android 2.0)WebView支持DOM,CSS和meta标签,以帮助适应不同密度屏幕。

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. However, if you specify the "target-densitydpi" meta property (discussed below), then you can stop this default scaling behavior.
  • 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.

  • The target-densitydpi property for the viewport meta tag. You can use this to specify the target density for which the web page is designed, using the following values:
    • device-dpi - Use the device's native dpi as the target dpi. Default scaling never occurs.
    • high-dpi - Use hdpi as the target dpi. Medium and low density screens scale down as appropriate.
    • medium-dpi - Use mdpi as the target dpi. High density screens scale up and low density screens scale down. This is also the default behavior.
    • low-dpi - Use ldpi as the target dpi. Medium and high density screens scale up as appropriate.
    •  - Specify a dpi value to use as the target dpi (accepted values are 70-400).

    Here's an example meta tag to specify the target density:

    <meta name="viewport" content="target-densitydpi=device-dpi" />

If you want to modify your web page for different densities, by using the -webkit-device-pixel-ratio CSS media query and/or the window.devicePixelRatio DOM property, then you should set the target-densitydpi meta property to device-dpi. This stops Android from performing scaling in your web page and allows you to make the necessary adjustments for each density via CSS and JavaScript.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值