android中Webview与javascript的交互(互相调用)

来源:互联网 发布:android 网络加载提示 编辑:程序博客网 时间:2024/05/22 03:25

MainActivity.java

package com.james.hybridapp;import android.os.Bundle;import android.os.Handler;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.webkit.WebSettings;import android.webkit.WebView;import android.widget.Toast;public class MainActivity extends AppCompatActivity {    private Handler mHandler = new Handler();    private WebView webView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        webView = (WebView) findViewById(R.id.webview);        WebSettings ws = webView.getSettings();        // 启用JavaScript        ws.setJavaScriptEnabled(true);        // 在载入assets目录下的一个页面        webView.loadUrl("file:///android_asset/index.html");        webView.addJavascriptInterface(new JavaScriptObject(MainActivity.this), "myObj");    }    public void onTest(View view){        webView.loadUrl("javascript:funFromjs()");        Toast.makeText(MainActivity.this, "调用javascript:funFromjs()", Toast.LENGTH_LONG).show();    }}
JavaScriptObject.java

package com.james.hybridapp;import android.content.Context;import android.widget.Toast;/** * Created by 1 on 2016/9/19. */public class JavaScriptObject {    Context mContxt;    public JavaScriptObject(Context mContxt) {        this.mContxt = mContxt;    }    public void fun1FromAndroid(String name) {        Toast.makeText(mContxt, name, Toast.LENGTH_LONG).show();    }    public void fun2(String name) {        Toast.makeText(mContxt, "调用fun2:" + name, Toast.LENGTH_SHORT).show();    }}

activity_main.xml

<?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">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:onClick="onTest"        android:text="点击下面测试"/>    <WebView        android:id="@+id/webview"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

在assets目录下放这个文件
index.html

<html><body><a>js中调用本地方法</a><script>    function funFromjs(){        document.getElementById("helloweb").innerHTML="HelloWebView,i'm from js";    }    var aTag = document.getElementsByTagName('a')[0];    aTag.addEventListener('click', function(){        //调用android本地方法        myObj.fun2("调用android本地方法fun1FromAndroid(String name)!!");        return false;    }, false);    </script><p></p><div id="helloweb"></div></body></html>


补充说明,4.4以上没有效果。


参考:http://blog.csdn.net/beyond0525/article/details/9374301

1 1