Android示例-JavaScript与UI控件交互(一)

本例将实现通过WebView控件的addJavascriptInterface()方法调用JavaScript脚本实现与UI控件的交互。源码如下:

1.MainActivity.java

public class MainActivity extends Activity {

    private Button mButtonMovement;
    private WebView mWebView;
    private String mStartRandomMoveJavaScript;
    private String mStopRandomMoveJavaScript;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int x = msg.arg1;
            int y = msg.arg2;

            mButtonMovement.layout(x, y,mButtonMovement.getMeasuredWidth() + x, mButtonMovement.getMeasuredHeight() + y);
        }
    };

    /**
     * 映射对象
     * 里面的方法必须使用@JavascriptInterface注解
     */
    class MyObject{
        @JavascriptInterface
        public void move(int x, int y){
            Message msg = new Message();
            msg.arg1 = x;
            msg.arg2 = y;
            handler.sendMessage(msg);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButtonMovement = findViewById(R.id.button3);
        mWebView = new WebView(this);
        WebSettings mWebSetting = mWebView.getSettings();
        mWebSetting.setJavaScriptEnabled(true);
        //第一个参数:要映射的对象  第二哥参数:映射对象的名字
        mWebView.addJavascriptInterface(new MyObject(),"demo");
        try {
            InputStream is = getResources().openRawResource(R.raw.start_radom_move);
            byte[] buffer = new byte[1024];

            int count = is.read(buffer);
            mStartRandomMoveJavaScript = new String(buffer, 0, count, "utf-8");

            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            //得到资源中的Raw数据流
            InputStream is = getResources().openRawResource(R.raw.stop_radom_move);
            //得到数据的大小
            int length = is.available();
            byte[] buffer = new byte[length];
            //读取数据
            is.read(buffer);
            mStopRandomMoveJavaScript = new String(buffer, 0, length, "utf-8");
            //关闭流
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void onClick_Start(View view){
        mWebView.loadDataWithBaseURL(null,mStartRandomMoveJavaScript, "text/html", "utf-8", null);
    }
    public void onClick_Stop(View view){
        mWebView.loadDataWithBaseURL(null,mStopRandomMoveJavaScript, "text/html", "utf-8", null);
    }
}
2.activity_main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lonly.example.javascripedemo.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginTop="27dp"
        android:layout_toStartOf="@+id/button2"
        android:onClick="onClick_Start"
        android:text="开始移动" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button"
        android:layout_alignBottom="@+id/button"
        android:layout_centerHorizontal="true"
        android:onClick="onClick_Stop"
        android:text="停止移动" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/button2"
        android:layout_centerVertical="true"
        android:text="移动的按钮" />

</RelativeLayout>

3.start_radom_move.js脚本文件

<script language="javascript">
var timer;
function startTimer()
{
    //设置定时器,定时执行randomMoveButton()函数
    timer = setInterval("randomMoveButton()",1000);
}
function randomMoveButton(){
    var x = Math.round(Math.random() * 300);
    var y = Math.round(100 + Math.random() * 400);
    //调用接口中的方法
    window.demo.move(x,y);
}
startTimer();
</script>

4.stop_radom_move.js脚本文件

<script language="javascript">
    clearInterval(timer);//清除定时器
</script>

运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值