项目需要Activity和JS进行数据交互,安卓端的实现找找资料看看还好理解,但是网页端是怎么实现的呢,仅以此文记录一下自己的成果
简单粗暴,咱们直接上代码
1.布局文件(h5_with_android_layout.xml)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/current_time_tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Current Time:" android:textSize="18sp" android:padding="10dp" /> <WebView android:id="@+id/main_webview" android:layout_width="match_parent" android:layout_height="match_parent"></WebView> </LinearLayout>
2.Activity页面 (Internet权限莫忘哈)
package com.ylz.h5withAndroid; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.TextView; import com.ylz.floatview.R; /** * Created by Administrator on 2016/10/26. */ public class H5WithAndroidActivity extends Activity{ WebView webView; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.h5_with_android_layout); init(); } private void init(){ webView=(WebView)findViewById(R.id.main_webview); textView=(TextView)findViewById(R.id.current_time_tv); initWebView(); } private void initWebView(){ WebSettings webSettings=webView.getSettings(); webSettings.setJavaScriptEnabled(true); webView.addJavascriptInterface(new JSInterfaces(), "H5WithAndroid"); webView.loadUrl("file:///android_asset/ylz/first.html"); } class JSInterfaces{ @JavascriptInterface public String setDate(){ Log.e("ylz","javascriptInterface setDate sunshine day! "); return "sunshine day!"; } @JavascriptInterface public void getDate(String getValue){ Log.e("ylz","javascriptInterface getDate getValue "+getValue); } @JavascriptInterface public void getCurrentTime(String weekday){ textView.setText(weekday); } } }3.网页(first.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>H5WithAndroid Demo</title> </head> <body> <h1 id="setDateH1"></h1> <p> <button οnclick="AndriodSetDate()">setDate</button> <script> function AndriodSetDate(){ document.getElementById("setDateH1").innerHTML=window.H5WithAndroid.setDate(); } </script> </p> <button οnclick="H5WithAndroid.getDate('8888')">getDate</button> <button οnclick="DayFunction()">getCurrentTime</button> <script> function DayFunction(){ var nowDay=new Date().getDay(); switch (nowDay){ case 0: nowDay="星期日" ; break; case 1: nowDay="星期一" ; break; case 2: nowDay="星期二" ; break; case 3: nowDay="星期三" ; break; case 4: nowDay="星期四" ; break; case 5: nowDay="星期五" ; break; case 6: nowDay="星期六" ; break; } window.H5WithAndroid.getCurrentTime(nowDay) } </script> </body> </html>
以此文留念一下自己的成果,也希望可以帮助到他人。