1.编写MyObject类实现要被调用的android方法
public class MyObject {
Context mcontext;
//构造函数传入上下文
public MyObject(Context c) {
mcontext=c;
}
@JavascriptInterface
public void showToast(String name){
//Toast打印消息
Toast.makeText(mcontext, name+",你好", Toast.LENGTH_LONG).show();
}
@JavascriptInterface
public void showList(){
//创建对话框
new AlertDialog.Builder(mcontext)
.setTitle("图书列表")
.setIcon(R.drawable.ic_launcher)
.setItems(new String[]{"bk1","bk2","bk3","bk4"},null)
.setPositiveButton("确定", null)
.create()
.show();
}
}
2.编写一个简单的html文件,尝试通过JavaScript调用myObj中的方法
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS调用android</title>
</head>
<body>
<input type="button" value="hi"
onclick="myObj.showToast('ywwuyi');">
<input type="button" value="list"
onclick="myObj.showList();">
</body>
</html>
3.在MainActivity中,通过将webSettings设置为允许通过JavaScript调用android方法,并为WebView添加JavaScript接口,将myObj指向MyObject类
@SuppressLint("JavascriptInterface")
public class MainActivity extends Activity {
WebView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=(WebView)findViewById(R.id.show);
view.loadUrl("file:///android_asset/test.html");
//通过将webSettings设置为允许通过JavaScript调用android方法
WebSettings webSettings=view.getSettings();
webSettings.setJavaScriptEnabled(true);
//为WebView添加JavaScript接口,将myObj指向MyObject类
view.addJavascriptInterface(new MyObject(this), "myObj");
}
}
运行程序,单击屏幕上的hi按钮或list按钮,将通过JavaScript调用MyObject中的android方法,打印消息或弹出对话框