步骤
1. 初始化。
WebView myWebView= (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
2. 设置支持javascript,默认为不可用。
WebSettings webSettings= myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
3 javascript访问android应用中方法。
webView.addJavascriptInterface(newJavaScriptInterface(this),"Android");
publicclass JavaScriptInterface{
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c){
mContext = c;
}
/** Show a toast from the web page */
publicvoid showToast(String toast){
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
<input type="button"value="Say hello"onClick="showAndroidToast('Hello Android!')"/>
<scripttype="text/javascript">
function showAndroidToast(toast){
Android.showToast(toast);
}
</script>
4 处理页面跳转。
myWebView.setWebViewClient
(newMyWebViewClient());
privateclass MyWebViewClientextends WebViewClient{
@Override
public booleanshouldOverrideUrlLoading
(WebView view, String url){
if(Uri.parse(url).getHost().equals("www.example.com")){
// This is my web site, so do not override; let my WebView load the page
returnfalse;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent= new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
returntrue;
}
}
5 访问历史(返回,前进)。
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack
(){
myWebView.goBack
();
returntrue;
}