Android js 互调

下面提供一个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.JavascriptInterface
			public 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() {
			@Override
			public void onClick(View v) {
				//java调用js
				webview.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>

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值