7.5.2 WebView和JavaScrip交互基础

Android基础入门教程——7.5.2 WebView和JavaScrip交互基础

标签(空格分隔): Android基础入门教程

本节引言:

在上一节中我们对Android的WebView(网页视图)进行了学习,相信已经了解了WebView的基本用法; 而本节我们要学习的就是通过:HTML -> JS ->Java来完成HTML5端与Android手机间的 互访!好的,话不多说,有吗有真相,让我们通过编写代码来体验这种微妙的联系吧~ PS:为了方便,本节用到的HTML都是以文件的形式放到assets目录下,只需通过 loadUrl(“file:///android_asset/~”)即可加载对应的HTML~

1.核心步骤讲解:

首先,我们定义一个类,用于将数据暴露出来,JS通过该类暴露的方法(Public)来调用Android! 接着,我们在WebView所在页面Activity,使用下述代码: webview.getSettings().setJavaScriptEnabled(true); webview.addJavascriptInterface(object,”name”); 然后js或者html中调用name.xxx调用对象里的暴露的方法: 比如: < input type=”button” value=”Toast提示” onclick=”name.showToast(‘呵呵’);”/> 另外,setJavaScriptEnabled是在Android 4.4以前的系统才有效!!!下一节我们会来讲解Android 4.4后 WebKit的变化以及要注意的地方!

2.使用示例讲解:1)HTML通过JS显示Toast与普通列表的对话框

运行效果图:

代码实现:

先准备我们的HTML文件,创建好后放到assets目录下:

demo1.html:

>Js调用Android>===>

自定义一个Object对象,js通过该类暴露的方法来调用Android

MyObject.java:

/** * Created by Jay on 2015/9/11 0011. */{private Context context;public MyObject(Context context) {this.context = context;}(String name) {Toast.makeText(context, name, Toast.LENGTH_SHORT).show();}() {new AlertDialog.Builder(context).setTitle(“联系人列表”).setIcon(R.mipmap.ic_lion_icon).setItems(new String[]{“基神”, “B神”, “曹神”, “街神”, “翔神”}, null).setPositiveButton(“确定”, null).create().show();}}

最后是MainActivity.java,启用JavaScript支持,然后通过addJavascriptInterface暴露对象~

{private WebView wView;(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);wView = (WebView) findViewById(R.id.wView);wView.loadUrl(“file:///android_asset/demo1.html”);WebSettings webSettings = wView.getSettings();//①设置WebView允许调用jswebSettings.setJavaScriptEnabled(true);webSettings.setDefaultTextEncodingName(“UTF-8”);//②将object对象暴露给Js,调用addjavascriptInterfacewView.addJavascriptInterface(new MyObject(MainActivity.this), “myObj”);}}2)HTML通过JS调用三种不同的对话框

运行效果图:

实现代码:

先往assets目录下塞一个html文件: demo2.html:

= “Content-Type” content=”text/html;charset=UTF-8″<=”JavaScript”>{alert(“Alert警告对话框!”);}{if(confirm(“访问百度?”)){location.href = “http://www.baidu.com”;}else alert(“取消访问!”);}{var word = prompt(“Prompt对话框”,”请输入点什么…:”);if(word){alert(“你输入了:”+word)}else{alert(“呵呵,你什么都没写!”);}}>>= “>==>Prompt对话框==></html>

PS:主布局和prompt布局这里就不贴了! 直接上MainActivity.java:

{private WebView wView;(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);wView = (WebView) findViewById(R.id.wView);//获得WebSetting对象,支持js脚本,可访问文件,支持缩放,以及编码方式WebSettings webSettings = wView.getSettings();webSettings.setJavaScriptEnabled(true);webSettings.setAllowFileAccess(true);webSettings.setBuiltInZoomControls(true);webSettings.setDefaultTextEncodingName(“UTF-8”);//设置WebChromeClient,处理网页中的各种js事件wView.setWebChromeClient(new MyWebChromeClient());wView.loadUrl(“file:///android_asset/demo2.html”);}//这里需要自定义一个类实现WebChromeClient类,并重写三种不同对话框的处理方法//分别重写onJsAlert,onJsConfirm,onJsPrompt方法class MyWebChromeClient extends WebChromeClient {(WebView view, String url, String message,final JsResult result) {//创建一个Builder来显示网页中的对话框new Builder(MainActivity.this).setTitle(“Alert对话框”).setMessage(message).setPositiveButton(“确定”, new OnClickListener() {(DialogInterface dialog, int which) {result.confirm();}}).setCancelable(false).show();return true;}(WebView view, String url, String message,final JsResult result) {new Builder(MainActivity.this).setTitle(“Confirm对话框”).setMessage(message).setPositiveButton(“确定”, new OnClickListener() {(DialogInterface dialog, int which) {result.confirm();}}).setNegativeButton(“取消”, new DialogInterface.OnClickListener() {(DialogInterface dialog, int which) {result.cancel();}}).setCancelable(false).show();return true;}(WebView view, String url, String message,String defaultValue, final JsPromptResult result) {//①获得一个LayoutInflater对象factory,加载指定布局成相应对象final LayoutInflater inflater = LayoutInflater.from(MainActivity.this);final View myview = inflater.inflate(R.layout.prompt_view, null);//设置TextView对应网页中的提示信息,edit设置来自于网页的默认文字((TextView) myview.findViewById(R.id.text)).setText(message);((EditText) myview.findViewById(R.id.edit)).setText(defaultValue);//定义对话框上的确定按钮new Builder(MainActivity.this).setTitle(“Prompt对话框”).setView(myview).setPositiveButton(“确定”, new OnClickListener() {(DialogInterface dialog, int which) {//单击确定后取得输入的值,传给网页处理String value = ((EditText) myview.findViewById(R.id.edit)).getText().toString();result.confirm(value);}}).setNegativeButton(“取消”, new OnClickListener() {(DialogInterface dialog, int which) {result.cancel();}}).show();return true;}}}3.HTML通过JS读取Android联系人并显示 想象困难做出的反应,不是逃避或绕开它们,

7.5.2 WebView和JavaScrip交互基础

相关文章:

你感兴趣的文章:

标签云: