標籤:android js互動
Android通過WebView載入js網頁代碼兩者之間互動
public class MainActivity extends Activity {private WebView webView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);webView = (WebView) findViewById(R.id.webView1);WebSettings webSettings = webView.getSettings();webSettings.setJavaScriptEnabled(true);//支援javascrip必須有webSettings.setDefaultTextEncodingName("utf-8");webView.addJavascriptInterface(this, "test");//對應js中的test.xxx,通過該標記來調用Android中的方法webView.setWebChromeClient(new WebChromeClient() {});//要加上這句,否則部分機型無法快顯視窗webView.loadUrl("http://192.168.3.4:8080/WebViewTest/test.html");//通過tomcat啟動一個網頁,當然本地的也行//webView.loadUrl("file:///android_asset/test.html");//放到assets目錄下即可}/** * js調用該方法 * @param msg */@JavascriptInterfacepublic void helloAndroid(String msg){ Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();}/** * 調用js中的方法 * @param v */public void call(View v){webView.post(new Runnable() { @Override public void run() { webView.loadUrl("javascript:callJS()"); Log.v("zd", "callJS"); } });}}
//xml布局,只有
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="call" android:text="Call JS" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" > <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </LinearLayout></LinearLayout>
//js代碼,其中通過前面聲明的test來引用android中的方法
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body><script type="text/javascript"> function show() { test.helloAndroid("text/javascript");//Android是在Android端定義的 } function callJS() { alert("HelloWebView, i‘m from js: "); } </script><input type="button" name="提交" value="提交" onclick="show();"></input></body></html>
650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/89/45/wKiom1gOBOHQYJIkAABtYvzFTDU910.png-wh_500x0-wm_3-wmp_4-s_541465495.png" title="QQ20161024205543.png" alt="wKiom1gOBOHQYJIkAABtYvzFTDU910.png-wh_50" />650) this.width=650;" src="http://s4.51cto.com/wyfs02/M01/89/43/wKioL1gOBUayTdQOAABEjPE4hLw068.png-wh_500x0-wm_3-wmp_4-s_2103317989.png" title="QQ20161024205723.png" alt="wKioL1gOBUayTdQOAABEjPE4hLw068.png-wh_50" />
本文出自 “爬過山見過海” 部落格,請務必保留此出處http://670176656.blog.51cto.com/4500575/1865182
Android與JS互動問題