记录使用 WebView 过程中的心得,便于参考
一、WebView 的基础使用
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
加载数据
WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://www.baidu.com"); // 从网址中加载网页
String data = "<html><body>test data <br/> 测试数据</body></html>";
webView.loadData(data, "text/html;charset=UTF-8", null); // 从字符串中加载网页
webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null); // 从字符串中加载网页
webView.loadUrl("file:///android_asset/html/index.html"); // 从 assets 目录下加载网页
webView.loadUrl("file:///mnt/sdcard/index.html"); // 从SD目录下卡加载网页
data = "<html><body>test data <br/> 测试数据 <br/> <img src='test.png'></body></html>";
webView.loadDataWithBaseURL("file:///android_res/drawable/", data, "text/html", "UTF-8", null); // 图片来自 res/drawable
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "UTF-8", null); // 图片来自 assets目录
webView.loadDataWithBaseURL("file:///mnt/sdcard/", data, "text/html", "UTF-8", null); // 图片来自 SDcard卡
data = "<html><body>test data <br/> 测试数据 <br/> <img src='/img/bd_logo.png'></body></html>";
webView.loadDataWithBaseURL("http://www.baidu.com", data, "text/html", "UTF-8", null); // 图片来自 网络
使用WebView加载网络数据,需添加访问网络的权限
<uses-permission android:name="android.permission.INTERNET" />
webView.getSettings().setJavaScriptEnabled(true); // JS支持,默认false
webView.getSettings().setSupportZoom(true); //设置使支持缩放, 默认true
webView.getSettings().setBuiltInZoomControls(false); //设置使支持缩放, 默认false
// 缓存相关
webView.getSettings().setAppCacheEnabled(true); // 启用应用缓存API,默认false
String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
webView.getSettings().setAppCachePath(appCacheDir); // 缓存路径,只调用一次
// 缓存模式
// WebSettings.LOAD_DEFAULT 默认的缓存模式
// WebSettings.LOAD_NORMAL 普通的缓存模式
// WebSettings.LOAD_CACHE_ELSE_NETWORK 有缓存就从缓存加载,不管缓存是否过期;无缓存从网络加载
// WebSettings.LOAD_NO_CACHE 不使用缓存,直接从网络加载
// WebSettings.LOAD_CACHE_ONLY 不使用网络,直接从缓存加载
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.getSettings().setDomStorageEnabled(true); // 设置DOM存储是否启用,默认false
webView.getSettings().setAppCacheMaxSize(1024*1024*8); //设置缓存最大值,
webView.clearCache(true); // 清除缓存
web中图片适应屏幕宽度
最简单的方法,修改html中img样式,设置图片 width="100%"
// <style>img{display: inline; height: auto; max-width: 100%;}</style>
webView.loadDataWithBaseURL(null, "<style>img{display: inline;height: auto;max-width: 100%;}</style>" + content, "text/html", "UTF-8", null);
web中修改文本字体颜色、大小
// <div style=\"color:#666666;font-size:13px\">显示的文本</div>
webView.loadDataWithBaseURL(null, "<style>img{display:inline;height:auto;max-width:100%;}</style><div style=\"color:#666666;font-size:13px\">" + introduction + "</div>", "text/html", "UTF-8", null);
web监听
WebViewClient 接收和处理各种通知和请求
WebChromeClient 处理JavaScript的对话框,网站图示,标题和进度
更多方法请参考API WebViewClient WebChromeClient
webView.setWebViewClient(new WebViewClient() {
// 使用当前WebView处理跳转
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true; // 不再向下传递
}
// 处理错误
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
ToastUtil.showToast(WebActivity.this, R.string.error_web);
}
// 页面开始加载
public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
pbLoad.setVisibility(View.VISIBLE);
}
// 页面加载完成
public void onPageFinished(WebView view, String url) {
pbLoad.setVisibility(View.GONE);
}
// 资源加载
public void onLoadResource(WebView view, String url) {
// 例如替换为本地资源
}
});
final Activity activity = this;
webView.setWebChromeClient(new WebChromeClient() {
// 加载进度
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("正在加载");
activity.setProgress(progress * 100);
if (progress == 100) {
activity.setTitle(R.string.app_name);
<span style="white-space:pre"> </span>}
}
});
浏览历史记录
返回键处理
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
// 或者使用以下方法
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
if (webView.canGoBack()) {
webView.goBack();
}
if (webView.canGoForward()) {
webView.goForward();
}
// 负数后退 正数前进
if (webView.canGoBackOrForward(-1)) {
webView.goBackOrForward(-1);
}
二、WebView与JS交互
这是个很有用的的功能,可以实现一些有意思的效果。
以下代码演示了两种交互
1. java 调用 javaScript ,弹出JS提示框
2. javaScript 调用 java,弹出Android Toast ;获取图片URL
html 这里是放在本地assets
<html>
<head><title>index</title></head>
<body>
<h2>test</h2>
<img src="ic_launcher.png">
<input type="button" value="hello Android" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
myInterface.showToast(toast);
}
function sayHello() {
alert("say hello");
}
</script>
</body>
</html>
java 代码
webView.loadUrl("javascript:sayHello()");
// 首先开启JS支持
webView.getSettings().setJavaScriptEnabled(true);
// 增加JS接口, 注意接口名和JS中的接口名要一致,这里是“myInterface”
webView.addJavascriptInterface(new WebAppInterface(this), "myInterface");
// 加载页面
webView.loadUrl("file:///android_asset/html/index.html");
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
addImageClickListner();
}
});
/**
* 注入js函数
*/
private void addImageClickListner() {
// 遍历img标签,添加点击事件,执行时调用本地接口传递图片的路径
// 注意,使用此方式会覆盖图片原有点击事件,如果之前有的话
// "myInterface" 对应前面 addJavascriptInterface 方法接口名
webView.loadUrl("javascript:(function(){"
+ "var objs = document.getElementsByTagName(\"img\");"
+ "for(var i=0;i<objs.length;i++) {"
+ " objs[i].onclick=function() {"
+ " window.myInterface.getImagePath(this.src);"
+ " }"
+ "}})()");
}
public class WebAppInterface {
Context mContext;
WebAppInterface(Context context) {
mContext = context;
}
// targetSdkVersion 为17或更高时必须添加注解
// @JavascriptInterface
public void showToast(String toast) {
ToastUtil.showToast(mContext, toast);
}
public void getImagePath(String imagePath) {
// 拿到图片的路径,就可以对图片进行处理
// 比如放大缩小图片之类
}
}
先到这里
以上
转载声明
http://blog.youkuaiyun.com/lxmy2012/article/details/39054667
官方文档
http://developer.android.com/reference/android/webkit/WebView.html
http://developer.android.com/reference/android/webkit/WebSettings.html
http://developer.android.com/guide/webapps/webview.html
其它参考
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2013/1010/1569.html