WebView加載本地html
loadUrl("file:///android_asset/html/index.html");
android調(diào)用js代碼
loadUrl("javascript:xxx()");
js調(diào)用android代碼
自定義對(duì)象交洗,實(shí)現(xiàn)調(diào)用方法(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--參數(shù):"+param;
}
</script>
</head>
<body>
<p id="content"></p>
<p>
<input type="button" value="調(diào)用Java方法" onclick="window.jstojava.showToast('來至JS的參數(shù)');" />
<input type="button" value="調(diào)用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");
//設(shè)置支持js
webview.getSettings().setJavaScriptEnabled(true);
//
findViewById(R.id.clickjs).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//調(diào)用JS方法绍赛,并傳遞參數(shù)
webview.loadUrl("javascript:invokedByJava('hello world')");
}
});
//js調(diào)用android代碼
webview.addJavascriptInterface(new JsToJava(MyWebViewActivity.this),"jstojava");
/*
當(dāng)WebView內(nèi)容影響UI時(shí)調(diào)用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;
}
});
}
}
自定義對(duì)象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 調(diào)用 js方法"
/>
<WebView
android:id="@+id/webeview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
最終效果