使javascript功能可用。这部分代码都放在UserListActivity中的onCreate()方法里。
然后是注册JS接口。先看看webview的一个方法。
public void addJavascriptInterface (Object obj, String interfaceName)
Since: API Level 1
Use this function to bind an object to JavaScript so that the methods can be accessed from JavaScript.
IMPORTANT:
· Using addJavascriptInterface() allows JavaScript to control your application. This can be a very useful feature or a dangerous security issue. When the HTML in the WebView is untrustworthy (for example, part or all of the HTML is provided by some person or process), then an attacker could inject HTML that will execute your code and possibly any code of the attacker's choosing.
Do not use addJavascriptInterface() unless all of the HTML in this WebView was written by you.
· The Java object that is bound runs in another thread and not in the thread that it was constructed in.
Parameters
|
obj |
The class instance to bind to JavaScript, null instances are ignored. |
|
interfaceName |
The name to used to expose the instance in JavaScript. |
我们在UserListActivity类的onCreate()方法中增加如下语句:
mWebView.addJavascriptInterface(this, "Android");
在UserListActivity类中增加如下方法:
public void user(String id) {
// 获取id,跳转activity。
}
这样当页面调用onclick="javascript:android.user('1')"语句的时候,就可以映射到UserListActivity对象的user()方法了。
这里user方法有一个参数,是要对应js语句的user(‘1’)。
下面附上所有代码。
Android部分的代码:
|
资源文件:
|
Web页面的局部代码:
<img src="……" onclick="javascript:android.user('1')" />
