WebView加载本地html
loadUrl("file:///android_asset/html/index.html");
android调用js代码
loadUrl("javascript:xxx()");
js调用android代码
自定义对象,实现调用方法(sdk>17需要添加注解)
webview.addJavascriptInterface(object,"xxx");
页面可以通过别名使用(window.xxx.方法名)
例子
<html>
<head>
<title>JS交互</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript">
function invokedByJava(param) {
document.getElementById("content").innerHTML = "android--参数:"+param;
}
</script>
</head>
<body>
<p id="content"></p>
<p>
<input type="button" value="调用Java方法" onclick="window.jstojava.showToast('来至JS的参数');" />
<input type="button" value="调用alert" onclick="alert('hello')" />
</p>
</body>
</html>
Activity
public class MyWebViewActivity extends BaseActivity{
private WebView webview;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_mywebview);
webview = (WebView) findViewById(R.id.webeview);
webview.loadUrl("file:///android_asset/test.html");
//设置支持js
webview.getSettings().setJavaScriptEnabled(true);
//
findViewById(R.id.clickjs).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//调用JS方法,并传递参数
webview.loadUrl("javascript:invokedByJava('hello world')");
}
});
//js调用android代码
webview.addJavascriptInterface(new JsToJava(MyWebViewActivity.this),"jstojava");
/*
当WebView内容影响UI时调用WebChromeClient的方法
*/
webview.setWebChromeClient(new WebChromeClient() {
/**
* 处理JavaScript Alert事件
*/
@Override
public boolean onJsAlert(WebView view, String url,
String message, final JsResult result) {
//用Android组件替换
new AlertDialog.Builder(MyWebViewActivity.this)
.setTitle("JS提示")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setCancelable(false)
.create().show();
return true;
}
});
}
}
自定义对象JsToJava
public class JsToJava {
private Context mContext;
/** Instantiate the interface and set the context */
public JsToJava(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();
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/clickjs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="android 调用 js方法"
/>
<WebView
android:id="@+id/webeview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
最终效果