如果本文帮助到你,本人不胜荣幸,如果浪费了你的时间,本人深感抱歉。
希望用最简单的大白话来帮助那些像我一样的人。如果有什么错误,请一定指出,以免误导大家、也误导我。
本文来自: http://www.jianshu.com/users/320f9e8f7fc9/latest_articles
感谢您的关注。
WebView在现在的项目中使用的频率应该还是非常高的。
我个人总觉得HTML5是一种趋势。找了一些东西,在此总结。
本篇最后有一个非常不错 的 Html5Activity 加载类,不想看的可以直接跳下载。
WebSettings
WebSettings webSettings = mWebView .getSettings();//支持获取手势焦点,输入用户名、密码或其他webview.requestFocusFromTouch();setJavaScriptEnabled(true); //支持jssetPluginsEnabled(true); //支持插件 设置自适应屏幕,两者合用setUseWideViewPort(true); //将图片调整到适合webview的大小 setLoadWithOverviewMode(true); // 缩放至屏幕的大小setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。setBuiltInZoomControls(true); //设置内置的缩放控件。 若上面是false,则该WebView不可缩放,这个不管设置什么都不能缩放。setDisplayZoomControls(false); //隐藏原生的缩放控件setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局 supportMultipleWindows(); //多窗口 setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 setAllowFileAccess(true); //设置可以访问文件 setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 setLoadsImagesAutomatically(true); //支持自动加载图片setDefaultTextEncodingName("utf-8");//设置编码格式
加载方式
加载一个网页:
webView.loadUrl(" http://www.google.com/");
加载apk包中的一个html页面
webView.loadUrl("file:///android_asset/test.html");
加载手机本地的一个html页面的方法:
webView.loadUrl("content://com.android.htmlfileprovider/sdcard/test.html");
WebViewClient
WebViewClient就是帮助WebView处理各种通知、请求事件的。
打开网页时不调用系统浏览器, 而是在本WebView中显示:
mWebView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } });
WebViewClient 方法
WebViewClient mWebViewClient = new WebViewClient() { shouldOverrideUrlLoading(WebView view, String url) 最常用的,比如上面的。 //在网页上的所有加载都经过这个方法,这个函数我们可以做很多操作。 //比如获取url,查看url.contains(“add”),进行添加操作 shouldOverrideKeyEvent(WebView view, KeyEvent event) //重写此方法才能够处理在浏览器中的按键事件。 onPageStarted(WebView view, String url, Bitmap favicon) //这个事件就是开始载入页面调用的,我们可以设定一个loading的页面,告诉用户程序在等待网络响应。 onPageFinished(WebView view, String url) //在页面加载结束时调用。同样道理,我们可以关闭loading 条,切换程序动作。 onLoadResource(WebView view, String url) // 在加载页面资源时会调用,每一个资源(比如图片)的加载都会调用一次。 onReceivedError(WebView view, int errorCode, String description, String failingUrl) // (报告错误信息) doUpdateVisitedHistory(WebView view, String url, boolean isReload) //(更新历史记录) onFormResubmission(WebView view, Message dontResend, Message resend) //(应用程序重新请求网页数据) onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,String realm) //(获取返回信息授权请求) onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) //重写此方法可以让webview处理https请求。 onScaleChanged(WebView view, float oldScale, float newScale) // (WebView发生改变时调用) onUnhandledKeyEvent(WebView view, KeyEvent event) //(Key事件未被加载时调用) }
将上面定义的WebViewClient设置给WebView:
webView.setWebViewClient(webViewClient);
WebChromeClient
WebChromeClient是辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等 :
方法中的代码都是由Android端自己处理。
WebChromeClient mWebChromeClient = new WebChromeClient() { //获得网页的加载进度,显示在右上角的TextView控件中 @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress < 100) { String progress = newProgress + "%"; } else { } } //获取Web页中的title用来设置自己界面中的title //当加载出错的时候,比如无网络,这时onReceiveTitle中获取的标题为 找不到该网页, //因此建议当触发onReceiveError时,不要使用获取到的title @Override public void onReceivedTitle(WebView view, String title) { MainActivity.this.setTitle(title); } @Override public void onReceivedIcon(WebView view, Bitmap icon) { // } @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { // return true; } @Override public void onCloseWindow(WebView window) { } //处理alert弹出框,html 弹框的一种方式 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { // return true; } //处理confirm弹出框 @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { // return true; } //处理prompt弹出框 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { // return true; }};
同样,将上面定义的WebChromeClient设置给WebView:
webView.setWebChromeClient(mWebChromeClient);
调用JS代码
WebSettings webSettings = mWebView .getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(getHtmlObject(), "jsObj");
上面这是前提!!!
然后实现上面的方法。
private Object getHtmlObject(){ Object insertObj = new Object(){ //给html提供的方法,js中可以通过:var str = window.jsObj.HtmlcallJava(); 获取到 public String HtmlcallJava(){ return "Html call Java"; } //给html提供的有参函数 : window.jsObj.HtmlcallJava2("IT-homer blog"); public String HtmlcallJava2(final String param){ return "Html call Java : " + param; } //Html给我们提供的函数 public void JavacallHtml(){ runOnUiThread(new Runnable() { @Override public void run() { //这里是调用方法 mWebView.loadUrl("javascript: showFromHtml()"); Toast.makeText(JSAndroidActivity.this, "clickBtn", Toast.LENGTH_SHORT).show(); } }); } //Html给我们提供的有参函数 public void JavacallHtml2(final String param){ runOnUiThread(new Runnable() { @Override public void run() { mWebView.loadUrl("javascript: showFromHtml2('IT-homer blog')"); Toast.makeText(JSAndroidActivity.this, "clickBtn2", Toast.LENGTH_SHORT).show(); } }); } }; return insertObj;}
Android 调用js有个漏洞:
http://blog.csdn.net/leehong2005/article/details/11808557WebView的方法
前进、后退
goBack () //后退goForward ()//前进goBackOrForward (int steps) //以当前的index为起始点前进或者后退到历史记录中指定的steps, 如果steps为负数则为后退,正数则为前进canGoForward () //是否可以前进canGoBack () //是否可以后退
清除缓存数据:
clearCache(true); //清除网页访问留下的缓存,由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.clearHistory () //清除当前webview访问的历史记录,只会webview访问历史记录里的所有记录除了当前访问记录.clearFormData () //这个api仅仅清除自动完成填充的表单数据,并不会清除WebView存储到本地的数据。
WebView的状态:
onResume () //激活WebView为活跃状态,能正常执行网页的响应onPause () //当页面被失去焦点被切换到后台不可见状态,需要执行onPause动过, onPause动作通知内核暂停所有的动作,比如DOM的解析、plugin的执行、JavaScript执行。pauseTimers () //当应用程序被切换到后台我们使用了webview, 这个方法不仅仅针对当前的webview而是全局的全应用程序的webview,它会暂停所有webview的layout,parsing,javascripttimer。降低CPU功耗。resumeTimers () //恢复pauseTimers时的动作。destroy () //销毁,关闭了Activity时,音乐或视频,还在播放。就必须销毁。
但是注意:webview调用destory时,webview仍绑定在Activity上.这是由于自定义webview构建时传入了该Activity的context对象,因此需要先从父容器中移除webview,然后再销毁webview:
rootLayout.removeView(webView); webView.destroy();
判断WebView是否已经滚动到页面底端 或者 顶端:
getScrollY() //方法返回的是当前可见区域的顶端距整个页面顶端的距离,也就是当前内容滚动的距离.
getHeight()或者getBottom() //方法都返回当前WebView 这个容器的高度
getContentHeight() 返回的是整个html 的高度,但并不等同于当前整个页面的高度,因为WebView 有缩放功能, 所以当前整个页面的高度实际上应该是原始html 的高度再乘上缩放比例. 因此,更正后的结果,准确的判断方法应该是:
if (webView.getContentHeight() * webView.getScale() == (webView.getHeight() + webView.getScrollY())) { //已经处于底端 } if(webView.getScrollY() == 0){ //处于顶端 }
返回键
返回上一次浏览的页面
public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); }
有一个非常不错的 Html5Activity 加载类帖出来:
package com.lyl.web;import android.graphics.Bitmap;import android.os.Bundle;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.KeyEvent;import android.webkit.GeolocationPermissions;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;import com.lyl.test.R;public class Html5Activity extends AppCompatActivity { private String mUrl; private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); Bundle bundle = getIntent().getBundleExtra("bundle"); mUrl = bundle.getString("url"); Log.d("Url:", mUrl); mWebView = (WebView) findViewById(R.id.web); WebSettings mWebSettings = mWebView.getSettings(); mWebSettings.setSupportZoom(true); mWebSettings.setLoadWithOverviewMode(true); mWebSettings.setUseWideViewPort(true); mWebSettings.setDefaultTextEncodingName("utf-8"); mWebSettings.setLoadsImagesAutomatically(true); //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface mWebSettings.setJavaScriptEnabled(true); saveData(mWebSettings); newWin(mWebSettings); mWebView.setWebChromeClient(webChromeClient); mWebView.setWebViewClient(webViewClient); mWebView.loadUrl(mUrl); } /** * 多窗口的问题 */ private void newWin(WebSettings mWebSettings) { //html中的_bank标签就是新建窗口打开,有时会打不开,需要加以下 //然后 复写 WebChromeClient的onCreateWindow方法 mWebSettings.setSupportMultipleWindows(true); mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true); } /** * HTML5数据存储 */ private void saveData(WebSettings mWebSettings) { //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置 mWebSettings.setDomStorageEnabled(true); mWebSettings.setDatabaseEnabled(true); mWebSettings.setAppCacheEnabled(true); String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath(); mWebSettings.setAppCachePath(appCachePath); } WebViewClient webViewClient = new WebViewClient(){ /** * 多页面在同一个WebView中打开,就是不新建activity或者调用系统浏览器打开 */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }; WebChromeClient webChromeClient = new WebChromeClient() { //=========HTML5定位========================================================== //需要先加入权限 //<uses-permission android:name="android.permission.INTERNET"/> //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } @Override public void onGeolocationPermissionsHidePrompt() { super.onGeolocationPermissionsHidePrompt(); } @Override public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false);//注意个函数,第二个参数就是是否同意定位权限,第三个是是否希望内核记住 super.onGeolocationPermissionsShowPrompt(origin, callback); } //=========HTML5定位========================================================== //=========多窗口的问题========================================================== @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(mWebView); resultMsg.sendToTarget(); return true; } //=========多窗口的问题========================================================== }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); }}
原谅我,忘了出自哪里,如果侵权请联系我,一定删除。
这是下载地址: http://yun.baidu.com/s/1eQWFDvG
觉得不错的点个喜欢呗,要是直接赞赏的话,那真是太荣幸了。
参考链接:
Android webview使用详解
Android WebView 开发详解(一)
还有一些零散的链接。

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools
