class Main6Activity : AppCompatActivity() {
private var contentWebView: WebView? = null
@SuppressLint("JavascriptInterface")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main6)
contentWebView = findViewById(R.id.webview) as WebView
contentWebView?.setBackgroundColor(Color.CYAN)
// 启用javascript
contentWebView!!.settings.javaScriptEnabled = true
// 从assets目录下面的加载html
contentWebView!!.loadUrl("file:///android_asset/web.html")
contentWebView!!.addJavascriptInterface(this@Main6Activity, "android")
//无参调用Js点击
findViewById(R.id.bt1).setOnClickListener {
// 无参数调用
contentWebView!!.loadUrl("javascript:javacalljs()")
}
//有参调用Js点击
findViewById(R.id.btn2).setOnClickListener {
// 传递参数调用
contentWebView!!.loadUrl("javascript:javacalljswith(" + "'http://blog.csdn.net/Leejizhou'" + ")")
}
}
//由于安全原因 需要加 @JavascriptInterface
@JavascriptInterface
fun startFunction() {
runOnUiThread { Toast.makeText(this@Main6Activity, "show", Toast.LENGTH_SHORT).show() }
}
@JavascriptInterface
fun startFunction(text: String) {
runOnUiThread { AlertDialog.Builder(this@Main6Activity).setMessage(text).show() }
}
}
<!DOCTYPE html>
<html>
<head>
<title>js 交互</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript">
function javacalljs(){
document.getElementById("content").innerHTML =
"<br\>JAVA";
}
function javacalljswith(arg){
document.getElementById("content").innerHTML =
("<br\>"+arg);
}
</script>
</head>
<body>
<h1><div id="content">js to navtive </div></h1>
<br/>
<input type="button" value="执行native方法无参" onclick="window.android.startFunction()" />
<br/>
<input type="button" value="执行native方法有参" onclick="window.android.startFunction('http://blog.csdn.net/Leejizhou')" />
</body>
</html>
网友评论