有話要說:
本篇主要總結了簡單的Android與js互相調用的方法。
在開發過程中遇到了需要在安卓中調用js方法的需求,於是將具體的實現過程總結成這篇博客。
效果:
其中“調用安卓方法”按鈕是html中的按鈕;“調用JS方法”按鈕是app中的按鈕。
本地HTML:
首先,在app根目錄新建一個assets文件夾,並在文件夾內新建一個本地html文件,如下圖
接着編寫一個簡單的html文件:
<html lang="zh-CN"> <p id='p'>hello world</p> <script> function test(){ document.getElementById("p").innerHTML += " 你好!" } </script> <button onclick="justTest.hello('js調用安卓方法!')">調用安卓方法</button> </html>
Android布局文件:
<?xml version="1.0" encoding="utf-8"?> <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" tools:context=".MainActivity"> <WebView android:id="@+id/webview" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="調用js方法" /> </LinearLayout>
安卓調用js方法:
可以看到,在本地html中已經有了一個test函數,下面來在安卓中調用這個test函數。
加載本地html文件:
webView = findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("file:///android_asset/show.html");
定義按鈕的點擊事件:
Button btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { testJS(); } });
其中testJS代碼為:
@SuppressLint("SetJavaScriptEnabled") public void testJS() { webView.loadUrl("javascript:test()"); }
據此,就實現了安卓調用js方法。
js調用安卓方法:
首先,需要在activity中定義被調用的方法:
@JavascriptInterface public void hello(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); }
並且需要給webview綁定上java對象:
webView.addJavascriptInterface(this, "justTest");
最后,在js中調用該方法:
<button onclick="justTest.hello('js調用安卓方法!')">調用安卓方法</button>
這樣就實現了在js中調用安卓方法。
總結:
由於工作繁忙,好久沒寫博客了。
以后會抽出時間多多總結自己在工作中所學習的內容的。
這篇博客寫了一個很簡單的一個demo,但是安卓和js互相調用在實際開發中很有用,特地做一個總結。
大家如果有什么疑問或者建議可以通過評論,歡迎大家的評論~