Android双击或多击事件

原理:双击,及时两次点击时间差比较小的单击事件,所以可以对单击事件进行加工处理,实现双击事件,或多击事件。

首先是双击事件:
1. 首先定义一个记录第一次点击事件的时间的变量
private long firstClickTime = 0;
2. 然后是就是对单击的事件进行监听修改。
逻辑为:当单击后,事件会对firstClickTime这个变量进行比较,如果是第一次单击,系统会记录这个单击时间。如果是第二次单击,事件会将第二次单击的当前时间减去第一次单击记录的事件,如果差值小于500毫秒(预设值),表示是我们希望的连续双击事件。

public void onClick(View source) {
        if (firstClickTime > 0) {
            if (System.currentTimeMillis() - firstClickTime < 500) {
                Toast.makeText(this, "hahah", 1).show();
                firstClickTime = 0;
            }
        } else {
            firstClickTime = System.currentTimeMillis();
        }
    }

多击事件:
1. 首先定义一个全局数组变量,数组的长度代表了你希望实现的多击事件的次数。
private long[] mHits=new long[3];
2. 然后就是处理事件。这里用到了一个知识点,以前从来没用过的方法。先上英文版

System.arraycopy(Object src, int srcPos, Object dst, int dstPos, int length)


Copies length elements from the array src, starting at offset srcPos, into the array dst, starting at offset dstPos. 
从源数组src的srcPos位置开始,复制长度为length长度的元素到目标数组dst的位置dstPos
The source and destination arrays can be the same array, in which case copying is performed as if the source elements are first copied into a temporary array and then into the destination array.

Parameters:参数
src the source array to copy the content.源数组
srcPos the starting index of the content in src.源数组要复制的起始位置;
dst the destination array to copy the data into.目的数组
dstPos the starting index for the copied content in dst.目的数组放置的起始位置
length the number of elements to be copied.复制的长度

以下是代码实现

public void multyClick(View view){
        //将mHits数组的第1位开始到数组的length位复制到数组mHits的第0位开始到第length-1位。
        System.arraycopy(mHits, 1, mHits, 0, mHits.length-1);
        mHits[mHits.length-1]=SystemClock.uptimeMillis();//将系统开机后开始计算的时间赋值给数组的最后一位。
        //如果数组最后一位的系统开机时间减去第0位的开机时间小于等于500毫秒(预设值),执行事件。
        if(mHits[0]>=(SystemClock.uptimeMillis()-500)){
            Toast.makeText(this, "点击了", 0).show();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值