WebView一般用法总结

时间:2024-10-15 08:05:01

下面是webview常规的用法:

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

//在Android 4.3系统及其一下WebView内部采用Webkit渲染引擎,在Android 4.4采用chromium 渲染引擎来渲染View的内容。

//别忘记,在androidMainFest.xml中添加网络权限
//<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
//<uses-permission android:name="android.permission.INTERNET" />
//<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

WebView test_wb;

JSUtil jsUtil;

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//原生和webview交互的类
jsUtil = new JSUtil();

//xml布局页面中定义
test_wb=(WebView)findViewById(R.id.test_wb);

//清理
//wv.clearCache(true);
//wv.clearHistory();
//wv.clearFormData();

//设置webview属性
WebSettings ws=test_wb.getSettings();
//一般都会设置支持js
ws.setJavaScriptEnabled(true);
//默认编码格式
ws.setDefaultTextEncodingName("UTF-8");
//设置页面自适应
ws.setUseWideViewPort(true);
//设置缓存模式
ws.setCacheMode(WebSettings.LOAD_NO_CACHE);
//……………………

//获取焦点
test_wb.requestFocus();
//注入webview对象
test_wb.addJavascriptInterface(jsUtil, "local_obj");//jsUtil对象类方法中添加了@JavascriptInterface标注,通过"window.local_obj.方法名"调用

//加载网页
test_wb.loadUrl("http://www.zjtax.net");
//加载本地地址,file://android_asset/test.html
// test_wb.loadUrl("file:///android_asset/test.html");----------------这里是file:/// 3个/线哦
//执行js,javascript:alert()
// test_wb.loadUrl("javascript:alert('ok')");

//主要处理解析,渲染网页等浏览器做的事情
//若不重写webviewclient的shouldOverrideUrlLoading方法,加载网页会默认用外部的浏览器打开//
test_wb.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView wb,String url)
{
test_wb.loadUrl(url);
return true;//表示手动处理,若没有loadUrl(url)页面不会跳转。

//return false;//若不想手动处理,直接用webview自动处理,可以直接返回false.

//return super.shouldOverrideUrlLoading(wb, url);
}

//页面开始请求
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}

//页面请求结束
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}

//页面有错误
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}

}

);

//是辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等
//重写处理网页的alert,confirm,Prompt ,Window,Progress
test_wb.setWebChromeClient(new WebChromeClient() {

//进度条
@Override
public void onProgressChanged(WebView view, int newProgress) {
pb.setProgress(newProgress);
if(newProgress==100){
pb.setVisibility(View.GONE);
}
}

//网站标题
@Override
public void onReceivedTitle(WebView view, String title) {
// TODO Auto-generated method stub
super.onReceivedTitle(view, title);
}

//网站图标
@Override
public void onReceivedTouchIconUrl(WebView view, String url,
boolean precomposed) {
// TODO Auto-generated method stub
super.onReceivedTouchIconUrl(view, url, precomposed);
}

//窗体
@Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
// TODO Auto-generated method stub
return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
}

@Override
public boolean onJsBeforeUnload(WebView view, String url,
String message, JsResult result) {
return super.onJsBeforeUnload(view, url, message, result);
}

/**
* 覆盖默认的window.alert展示界面,避免title里显示为“:来自file:////”
*/

public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

builder.setTitle("对话框")
.setMessage(message)
.setPositiveButton("确定", null);

// 不需要绑定按键事件
// 屏蔽keycode等于84之类的按键
builder.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
Log.v("onJsAlert", "keyCode==" + keyCode + "event="+ event);
return true;
}
});
// 禁止响应按back键的事件
builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
result.confirm();// 因为没有绑定事件,需要强行confirm,否则页面会变黑显示不了内容。
return true;
// return super.onJsAlert(view, url, message, result);
}

/**
* 覆盖默认的window.confirm展示界面,避免title里显示为“:来自file:////”
*/
public boolean onJsConfirm(WebView view, String url, String message,
final JsResult result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("对话框")
.setMessage(message)
.setPositiveButton("确定",new OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
result.confirm();
}
})
.setNeutralButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
builder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});

// 屏蔽keycode等于84之类的按键,避免按键后导致对话框消息而页面无法再弹出对话框的问题
builder.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
Log.v("onJsConfirm", "keyCode==" + keyCode + "event="+ event);
return true;
}
});
// 禁止响应按back键的事件
// builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
return true;
// return super.onJsConfirm(view, url, message, result);
}

/**
* 覆盖默认的window.prompt展示界面,避免title里显示为“:来自file:////”
* window.prompt('请输入您的域名地址', '618119.com');
*/
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

builder.setTitle("对话框").setMessage(message);

final EditText et = new EditText(view.getContext());
et.setSingleLine();
et.setText(defaultValue);
builder.setView(et)
.setPositiveButton("确定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm(et.getText().toString());
}

})
.setNeutralButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});

// 屏蔽keycode等于84之类的按键,避免按键后导致对话框消息而页面无法再弹出对话框的问题
builder.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
Log.v("onJsPrompt", "keyCode==" + keyCode + "event="+ event);
return true;
}
});

// 禁止响应按back键的事件
// builder.setCancelable(false);
AlertDialog dialog = builder.create();
dialog.show();
return true;
// return super.onJsPrompt(view, url, message, defaultValue,
// result);
}

});

}
}