@cxm-2016
2016-09-19T17:57:55.000000Z
字数 1356
阅读 1926
android
js
no
@android.webkit.JavascriptInterface
fun showToast(name: String) {
Toast.makeText(this, name, Toast.LENGTH_SHORT).show()
}
给方法声明@android.webkit.JavascriptInterface
后表明该方法允许JS代码调用
<!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="打招呼" onclick="myObj.showToast('孙悟空');"/>
</body>
</html>
这里调用了上面提供的showToast
方法
val settings = mmWebView.settings
settings.javaScriptEnabled = true
mmWebView.addJavascriptInterface(object, "myObj")
第一句取出WebView的设置对象,第二句允许执行JS代码,第三句发送方法所在的对象,并将方法命名为myObj
class MiniBrowserActivity : AppCompatActivity() {
val js = """
<!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="打招呼" onclick="myObj.showToast('孙悟空');"/>
</body>
</html>
"""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_mini_browser)
val settings = mmWebView.settings
settings.javaScriptEnabled = true
mmWebView.addJavascriptInterface(this, "myObj")
mmWebView.loadData(js, "text/html;charset=utf-8", "utf-8")
}
@android.webkit.JavascriptInterface
fun showToast(name: String) {
Toast.makeText(this, name, Toast.LENGTH_SHORT).show()
}
}