Android WebView使用笔记

来源:互联网 发布:茅场晶彦 知乎 编辑:程序博客网 时间:2024/04/30 14:46

1.webview主要调用三个方法

a、LoadUrl        直接加载网页、图片并显示。(本地或是网络上的网页、图片、gif)

b、LoadData     显示文字与图片内容 (模拟器1.5、1.6)

c、LoadDataWithBase  显示文字与图片内容(支持多个模拟器版本)

2.webview通过getsettings方法来获取WebSetting对象,来对WebView进行一些设置

setJavaScriptEnabled(true); //支持jssetPluginsEnabled(true); //支持插件setUseWideViewPort(false); //将图片调整到适合webview的大小setSupportZoom(true); //支持缩放setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局supportMultipleWindows(); //多窗口setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存setAllowFileAccess(true); //设置可以访问文件setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点webview webSettings.setBuiltInZoomControls(true); //设置支持缩放setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口setLoadWithOverviewMode(true); // 缩放至屏幕的大小setLoadsImagesAutomatically(true); //支持自动加载图片

3.WebView有两个方法setWebChromeClient和setWebClient

setWebChromeClient主要处理解析,渲染网页等浏览器做的事情

WebChromeClient是辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等 

onCloseWindow(关闭WebView) onCreateWindow() onJsAlert (WebView上alert是弹不出来东西的,需要定制你的WebChromeClient处理弹出) onJsPrompt onJsConfirm onProgressChanged onReceivedIcon onReceivedTitle
例如:js中的alert,如果不重写onJsAlert方法,那么在webview中的alert事件是没有反应的,需要重写onJsAlert方法

private class MyWebChromeClient extends WebChromeClient {@Overridepublic boolean onJsAlert(WebView view, String url, String message, JsResult result) {Toast.makeText(MainActivity.this, "Alert", Toast.LENGTH_SHORT).show();return true;//这里返回true,值提示Alert,并且后续无法在弹出alert}}

private class MyWebChromeClient extends WebChromeClient {@Overridepublic boolean onJsAlert(WebView view, String url, String message, JsResult result) {Toast.makeText(MainActivity.this, "Alert", Toast.LENGTH_SHORT).show();return false;//这里返回false,值提示Alert,并且弹出alert弹窗,可多次点击}}

WebViewClient就是帮助WebView处理各种通知、请求事件的,具体来说包括:

onLoadResource onPageStart onPageFinish onReceiveError onReceivedHttpAuthRequest 

4.webview和js交互

首先需要创建一个与js交互的对象,提供一些供js调用的方法

final class DemoJavaScriptInterface {DemoJavaScriptInterface() {}/** * api17以上,必须要在被调用的方法上加上注解@JavascriptInterface */@JavascriptInterfacepublic void clickOnAndroid() {mHandler.post(new Runnable() {public void run() {mWebView.loadUrl("javascript:wave()");//js函数}});}}

注意:在API17以上的机器上运行,必须要在被调用的方法前加上注解@JavascriptInterface并且方法必须为publi修饰的

谷歌官方文档说明


创建对象以后,就为JS添加这个对象

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
然后在Html文件中直接调用这个对象“demo”的方法就行了

onClick="window.demo.clickOnAndroid()"


0 0
原创粉丝点击