WebView与JS交互
来源:互联网 发布:sql declare 用法 编辑:程序博客网 时间:2024/06/06 01:46
基本步骤:
1)定义一个类,将数据暴露出来,JS通过该类暴露的public方法来调用Android!
2)在WebView所在页面的Activity中,使用下述代码:
webview.getSettings().setJavaScriptEnabled(true);webview.addJavascriptInterface(object,"name");
然后在js或者html中通过name.xxx调用对象里暴露的相应方法:
比如:
< input type="button" value="Toast提示" onclick="name.showToast('Hello, world!');"/>
注意事项:
setJavaScriptEnabled在Android 4.4以前的系统才有效!
例子:
demo.html
<html><head> <title>Js调用Android</title></head><body><input type="button" value="Toast提示" onclick="Demo.showToast('Hello, world!');"/><input type="button" value="列表对话框" onclick="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>
0 0
- webview与js交互
- webview与js交互
- webview与js交互
- webview与js交互
- webview与js交互
- webview与js交互
- WebView与JS交互
- webView与js交互
- webView与js交互
- webview与js交互
- webview与js交互
- webview与js交互
- webview与js交互
- WebView与JS交互
- webview与js交互
- Webview 与JS 交互
- webview与js交互
- WebView与Js交互
- JDBC连接MySQL 插入中文数据的乱码问题
- [LeetCode]Longest Valid Parentheses
- 常用NLP知名研究机构
- Fire Again
- asp.net 中GridView控件实现全选及反选的功能
- WebView与JS交互
- Java 实现邮件的自动发送
- asp.net 中GridView控件实现全选及反选的功能
- 在GridView中针对鼠标单击的某一独立单元格进行编辑
- oracle 定义双重循环例子
- <shape> android 各属性介绍
- 【栈】两栈共享空间
- 工业4.0——世界不再是你过去所知道的那样
- CentOS6.x安装memcaches1.4.x