android js互調例子

來源:互聯網
上載者:User

下面提供一個android與js互調的簡單樣本

(1) android 中 通過該方法調用執行Js中的jsGetTextValue()方法: webview.loadUrl("javascript:jsGetTextValue()");

(2) js中通過addJavascriptInterface設定介面名為jsIntr,然後js中即可直接引用該對象,通過該對象調用java的方法javaSetText();

注意:android4.4以上的版本在addJavascriptInterface中添加的介面方法都必須加上這個首碼 "@android.webkit.JavascriptInterface" ,否則js無法調用java。

1、測試html檔案,存放位置 assets / html / test.html

<html>    <body>        <form action="#" method="get">            <p>1 name: <input id="text1" type="text" name="text1" value="1"/></p>            <input type="button" value="button1_value" name="button1_name" onclick="jsGetTextValue()"/>        </form>        <script type="text/javascript">            function jsGetTextValue() {                //js調用java                window.jsIntr.javaSetText(document.getElementById("text1").value);            }        </script>    </body></html>

2、android代碼,WebActivity.java

public class WebActivity extends Activity {    private WebView webview;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);setContentView(R.layout.activity_web);webview = (WebView) findViewById(R.id.webview);button = (Button) findViewById(R.id.button);//允許html執行JS指令碼,如果不進行設定的話,JS函數無法生效webview.getSettings().setJavaScriptEnabled(true);//在設定JS調用java方法的介面對象,在JS中可以直接存取該對象,然後調用該對象的方法間接地執行java代碼webview.addJavascriptInterface(new Object() {@android.webkit.JavascriptInterfacepublic void javaSetText(String text) {Log.e("text value", text);}//jsIntr是介面名,使用在js中,為調用的java方法的對象}, "jsIntr");webview.loadUrl("file:///android_asset/html/test.html");button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//java調用jswebview.loadUrl("javascript:jsGetTextValue()");});}}

3、布局檔案 activity_web.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <Button        android:id="@+id/button"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:text="Get Value" />    <WebView        android:id="@+id/webview"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_above="@id/button" /></RelativeLayout>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.