加載webview的類
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JavaScriptInterface JSInterface;
WebView wv;
wv = (WebView) findViewById(R.id.wv_test);
wv.getSettings().setJavaScriptEnabled(true); ///------- 設(shè)置javascript 可用
JSInterface = new JavaScriptInterface(this); ////------
wv.addJavascriptInterface(JSInterface, "JSInterface"); // 設(shè)置js接口 第一個(gè)參數(shù)事件接口實(shí)例阅虫,第二個(gè)是實(shí)例在js中的別名母剥,這個(gè)在js中會(huì)用到
wv.loadUrl("file:///android_asset/test.html");
}
}
JavaScriptInterface類
public class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void doSomething() {
//點(diǎn)擊webwiew網(wǎng)頁里按鈕時(shí)候要做的事
}
}
webview
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
JSInterface.doSomething();
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>