webview最全面详解(一)了解官方文档,androidstudio开发实战pdf

WebView是Android中用于展示网页的组件,它基于WebKit内核。要使用WebView,需要在AndroidManifest.xml中添加INTERNET权限。默认情况下,WebView不提供浏览器功能,需手动设置JavaScript支持和错误处理。可以通过WebChromeClient和WebViewClient定制行为,如显示进度、处理错误。本文翻译官方文档,详细介绍WebView的基本使用和定制方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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文件中:

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 = “You scored 192 points.”;

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(String,String,String)。

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 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存储——它不与浏览器应用共享数据。

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:

最后,如果大伙有什么好的学习方法或建议欢迎大家在评论中积极留言哈,希望大家能够共同学习、共同努力、共同进步。

小编在这里祝小伙伴们在未来的日子里都可以 升职加薪,当上总经理,出任CEO,迎娶白富美,走上人生巅峰!!

不论遇到什么困难,都不应该成为我们放弃的理由!

很多人在刚接触这个行业的时候或者是在遇到瓶颈期的时候,总会遇到一些问题,比如学了一段时间感觉没有方向感,不知道该从那里入手去学习,需要一份小编整理出来的学习资料的关注我主页或者点击我的GitHub免费领取~

这里是关于我自己的Android 学习,面试文档,视频收集大整理,有兴趣的伙伴们可以看看~

如果你看到了这里,觉得文章写得不错就给个赞呗?如果你觉得那里值得改进的,请给我留言,一定会认真查询,修正不足,谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值