先看一下效果图
准备工作
1.简单的.html文件,将它放在Tomcat文件目录下
X:\Program Files\apache-tomcat-7.0.53\webapps\ROOT
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function showAndroidToast() {
window.Android.callAndroid();
}
function changeInputValue(content){
document.getElementById("put_id").value=content;
}
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="showAndroidToast()"/>
<input type="text" value="aa" id="put_id"/>
</body>
</html>
2.简单的布局及权限问题
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<Button
android:id="@+id/bt_loadjs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="调用JavaScript方法"
/>
<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
3.进行通讯
package com.oblivion.android2js;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Bind(R.id.bt_loadjs)
Button btLoadjs;
@Bind(R.id.wv)
WebView wv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
wv.setWebChromeClient(new WebChromeClient());//设置能够使js正常弹窗
wv.addJavascriptInterface(new JavaScripeCallBack(),"Android");
wv.loadUrl("http://10.0.3.2:8080/test.html");
setType();
}
/**
* 设置硬件加速问题
*/
private void setType() {
if (Build.VERSION.SDK_INT >= 11) {
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public class JavaScripeCallBack {
@JavascriptInterface
public void callAndroid() {
Toast.makeText(MainActivity.this, "Android", Toast.LENGTH_SHORT).show();
}
}
@OnClick(R.id.bt_loadjs)
public void onClick() {
wv.loadUrl("javascript:changeInputValue('JavaScript')");
}
}
4.需要特别注意的地方
/**
* 设置硬件加速问题
*/
private void setType() {
if (Build.VERSION.SDK_INT >= 11) {
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}