1、现在开发的App与H5进行交互的地方用到的还是很多的。接下主要从两个方面简答介绍下:
Android界面上展示webView(加载个H5页面)
布局文件中添加webView,初始化次控件:
<WebView android:id="@+id/web_View" android:layout_weight="3" android:layout_width="match_parent" android:layout_height="match_parent"> </WebView>
在类中
web_View = findViewById(R.id.web_View);
注意这里要给webView设置属性,比如:
settings = web_View.getSettings(); settings.setJavaScriptEnabled(true); //支持js settings.setDomStorageEnabled(true);//这个解决web界面展示不全的情况 web_View.addJavascriptInterface(this, "android");
当然还有很多其他的属性,可按需设置。
自己测试的时候可以在本地创建一个html页面,在里面添加一些控件:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title></head> <body> <button id="btn1">开始</button> <button id="btn2">结束</button> <div id="content"></div> </body>
document.getElementById("btn1").onclick = function(){ //android是传过来的对象名称,setmessage是android中的方法 android.startVoice(); }; document.getElementById("btn2").onclick = function(){ android.stopVoice(); } function CallBackVoice(arg){ document.getElementById("content").innerHTML = ("<br\>"+arg); } </script> </html> 在main下创建assets文件夹存放我们的html,然后再直接loadUrl web_View.loadUrl("file:////android_asset/js_java_interaction.html");
String url = "javascript:CallBackVoice('" + "Android返回的数据"+ "')";//Android调用H5中的方法。 web_View.loadUrl(url);
@JavascriptInterface public void startVoice() { Toast.makeText(this, "开始", Toast.LENGTH_LONG).show(); }
@JavascriptInterface public void stopVoice() { Toast.makeText(this, "结束:", Toast.LENGTH_LONG).show(); }