android中引用javascript和在javascript中引用java的简单例子

在android中通过微webView是可以加载javascript代码的,与其说是javascript不如说是加载网页,其实就是html和javascript的结合等,通过html和javascript也可以创建安卓应用,因为android和javascript可以相互调用,下面是我介绍的一个简单的例子,大家可以参考。欢迎和大家一起交流。

//允许JavaScript执行
webSettings.setJavaScriptEnabled(true);

// 添加一个对象, 让javascript可以访问该对象的方法,
myWebView.addJavascriptInterface(new WebAppInterface(this),
"myInterfaceName");

//java中调用javascript中的方法
myWebView.loadUrl("javascript:myFunction()");

具体的大家看代码分析吧,这个简单的列子其实很容易明白的

package com.mlf.javascripttest;import android.os.Bundle;import android.annotation.SuppressLint;import android.app.Activity;import android.content.Context;import android.view.View;import android.view.View.OnClickListener;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;import android.webkit.JsResult;import android.widget.Button;import android.widget.Toast;//@SuppressLint("SetJavaScriptEnabled")@SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })public class MainActivity extends Activity {private WebView myWebView;private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        myWebView=(WebView) findViewById(R.id.javascriptWebview);        button=(Button) findViewById(R.id.uttonId);        WebSettings webSettings=myWebView.getSettings();        //允许JavaScript执行        webSettings.setJavaScriptEnabled(true);        webSettings.setDefaultTextEncodingName("GBK");         myWebView.setWebViewClient(new WebViewClient());                 myWebView.setWebChromeClient(new WebChromeClient()            {                @Override                public boolean onJsAlert(WebView view, String url, String message,                        JsResult result)                {                    // TODO Auto-generated method stub                    return super.onJsAlert(view, url, message, result);                }            });        // 添加一个对象, 让javascript可以访问该对象的方法,         myWebView.addJavascriptInterface(new WebAppInterface(this),                    "myInterfaceName");            // 载入页面:本地html资源文件,放在assets文件夹下            myWebView.loadUrl("file:///android_asset/javascripttest.html");            button.setOnClickListener(new OnClickListener() {                                @Override                public void onClick(View arg0) {                    // TODO Auto-generated method stub                    //java中调用javascript中的方法                    myWebView.loadUrl("javascript:myFunction()");                }            });    }                  class WebAppInterface{            Context mContext;            WebAppInterface(Context c){                mContext=c;            }            public void showToast(String toast){                Toast.makeText(mContext, toast, Toast.LENGTH_LONG).show();            }         }                }

javascript xml文件

<html><head><h1>This is a HTML Page</h1><!-- JavaScript脚本,主要包括了按钮要执行的函数,显示对话框等 --><script type="text/javascript">    //JavaScript方法,弹出对话框显示信息    function myFunction()    {        alert("Hello World!");    }    function onAlert()    {        console.log("onAlert method");//显示调试信息        alert("This is a alert sample from html");    }    function onConfirm()    {        console.log("onConfirm method");        var b = confirm("are you sure to login?");        alert("your choice is " + b);    }    function onPrompt()    {        console.log("onPrompt method");        var b = prompt("please input your password", "aaa");        alert("your input is " + b);    }    //调用绑定的Java对象的方法,即调用Android代码显示对话框    function showAndroidToast(toast)    {        console.log("showAndroidToast method");        myInterfaceName.showToast(toast);//注意此处的myInterfaceName要和外部传入的名字一致,大小写正确    }</script></head><body>        <p>        <!-- 前四个按钮调用JS函数 -->        JavaScript函数调用 <br />        <button onclick="myFunction()">点击这里!</button>        <br />         <input type="button" value="alert" onclick="onAlert()" /> <br />        <input type="button" value="confirm" onclick="onConfirm()" /> <br />        <input type="button" value="prompt" onclick="onPrompt()" /><br />        <!-- 上面用了两种定义按钮的方式,效果一样的 -->    </p>        <p>        <!-- 这个Say hello 按钮调用Android代码中的方法 -->        用JavaScript按钮调用Android代码 <br />         <input type="button"            value="Say hello" onClick="showAndroidToast('Hello Android!')" />    </p>    <a href="http://www.google.com" />Google    </a></body></html>

布局文件xml

<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"     >    <TextView        android:layout_width="match_parent"        android:layout_height="30dp"        android:text="javascript和android相互调用"         android:textSize="20dp"        android:gravity="center"        android:id="@+id/textView1"/>    <WebView        android:layout_below="@+id/textView1"       android:id="@+id/javascriptWebview"        android:layout_width="match_parent"       android:layout_height="380dp"/>    <Button         android:id="@+id/uttonId"        android:layout_below="@+id/javascriptWebview"        android:layout_width="match_parent"        android:layout_height="50dp"        android:textSize="20dp"        android:gravity="center"        android:text="android调用javascript"/></RelativeLayout>

谢谢大家参考借鉴,有机会多多交流!欢迎提出疑问,或有新的领先技术学习!

更多相关文章

  1. The import com.google cannot be resolved解决方法
  2. 在Android中解析ls 命令得到目录列表的方法
  3. Android统计EditText的字母数字以及汉字的统计方法
  4. Android setContentView方法解析(一)
  5. Android 键盘挤压 按钮
  6. Android与Vue的交互的方法示例

随机推荐

  1. android 下载图片到本地 sdcard
  2. Android(安卓)6.0 读写SD卡权限问题(续)
  3. [置顶] Android通过tcpdump抓包
  4. Android(安卓)ZoomControls放大缩小图片
  5. android 铃声设置流程讲解
  6. Android(安卓)Weekly Notes Issue #223
  7. Windows 7 部署 Android(安卓)开发环境傻
  8. android Menory 小结
  9. Android资源加载机制
  10. [Android(安卓)SQLite]数据存储与访问 -