Android双击或多击事件

来源:互联网 发布:2015中国石油进口数据 编辑:程序博客网 时间:2024/06/02 03:15

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

首先是双击事件:
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的位置dstPosThe 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();        }    }
0 0
原创粉丝点击