WebView与JS交互

基本步骤:

1)定义一个类,将数据暴露出来,JS通过该类暴露的public方法来调用Android!

2)在WebView所在页面的Activity中,使用下述代码:

webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(object,"name");

然后在js或者html中通过name.xxx调用对象里暴露的相应方法:
比如:

 < input type="button" value="Toast提示" οnclick="name.showToast('Hello, world!');"/>

注意事项:

setJavaScriptEnabled在Android 4.4以前的系统才有效!


例子:

demo.html

<html>
	<head>
    	<title>Js调用Android</title>
	</head>

	<body>
		<input type="button" value="Toast提示" οnclick="Demo.showToast('Hello, world!');"/>
		<input type="button" value="列表对话框" οnclick="Demo.showDialog();"/>
	</body>
</html>


package com.example.hello;

import android.app.AlertDialog;
import android.content.Context;
import android.widget.Toast;

public class Demo {
	private Context context;

	public Demo(Context context) {
		this.context = context;
	}

	//将显示Toast和对话框的方法暴露给JS脚本调用
    public void showToast(String name) {
        Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
    }

    public void showDialog() {
        new AlertDialog.Builder(context)
                .setTitle("联系人列表")
                .setItems(new String[]{"aaa", "bbb", "ccc", "ddd", "eee"}, null)
                .setPositiveButton("确定", null).create().show();
    }
}

package com.example.hello;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class MainActivity extends Activity {
	private WebView webView;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView=(WebView)findViewById(R.id.webView);
        webView.loadUrl("file:///android_asset/demo.html");
        
        WebSettings webSettings=webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webView.addJavascriptInterface(new Demo(MainActivity.this), "Demo");
    }
}

<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp" />

</RelativeLayout>






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值