先看效果圖。
圖中展示了 Android 調用 js中的方法 和 js 調用Android中的方法。
佈局代碼 一個按鈕,一個WebView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="安卓調用js中的方法"
/>
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
main目錄下創建 assets文件夾 再創建js.html文件
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" >
<title>Java與html中JavaScript方法互調</title>
<script type="text/javascript">
function showAlert(){
alert("佛系三連: 可以、都行、沒關係");
}
function showAndroidToast(){
js.showAndroidToast();
}
</script>
</head>
<body>
<div>
<input type="button" onclick="showAlert()" value="js展示彈窗">
</div>
<div>
<input type="button" onclick="showAndroidToast()" value="js調用Android中的方法">
</div>
</body>
</html>
在Activity中對WebView和 Button 初始化並使用WebView加載 js.html文件。
public class MainActivity extends Activity {
private WebView mWebView;
private JsInterface mJsInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mJsInterface.showAlert();
}
});
mJsInterface = new JsInterface(this);
initWeb();
}
private void initWeb() {
WebSettings setting = mWebView.getSettings();
setting.setJavaScriptEnabled(true);//開啓js支持
//在webview中打開url,不使用其他瀏覽器。
mWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
//必須設置,不設置的話無法彈出alert。
mWebView.setWebChromeClient(new WebChromeClient());
//加載文件
mWebView.loadUrl("file:///android_asset/js.html");
mWebView.addJavascriptInterface(mJsInterface,"js");
}
class JsInterface{
private Context mContext;
public JsInterface(Context context) {
mContext = context;
}
//安卓調用js中的方法
@JavascriptInterface
public void showAlert(){
mWebView.loadUrl("javascript:showAlert()");
}
//js調用安卓中的方法
@JavascriptInterface
public void showAndroidToast(){
Toast.makeText(mContext,"點餐三連: 不餓、你選、都可以",Toast.LENGTH_SHORT).show();
}
}
}
運行就可以看出效果。