简介
android中使用webview可以很方便的加载网页,
在做例如新闻详情的时候会非常方便。
1. 布局
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
2. 权限(既然请求网页肯定要联网)
<manifest ... >
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
3.使用webview加载页面
⑴加载网页
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
⑵加载本地页面(注意html页面放在资源目录assets下<pre name="code" class="html">myWebView.loadUrl("file:///android_asset/XX.html");
4.页面中js,允许JS执行(这里通过getSetting()方法拿到webSettings,从而设置当前的wevview允许js执行,有的js代码就算设置这个也不会执行,这个在后面的内容中会讲到)
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
5. 绑定js和webview(通过一个接口),实现js和android互调
这里为什么要把js和webview绑定到一起呢?因为这样就可以js和android的代码互相调用。google官方推荐这种方式替换html的alert。
注意点:如果你的targetSdkVersion版本在17以上,必须添加这样一个注解
@JavascriptInterface.不然加载webview的时候,这个接口就是无效的.
⑴ 接口:
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
⑵ js代码(js调用接口中方法,弹一个土司)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
⑶android端代码
WebView webView = (WebView) findViewById(R.id.webview);
WebView.getSettings().setJavaScriptEnabled(true);//注意这里一定要加
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
效果图:
6.重写返回按钮,不然点击back的时候就会退出。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}