Android进阶——双击,三击和多击的实现

来源:互联网 发布:网络教育统考不通过率 编辑:程序博客网 时间:2024/05/29 08:36

双击:

先来看简单的实现方式

   private void initView() {        // 找到按钮控件        btn = (Button) findViewById(R.id.button);        // 设置点击事件监听        btn.setOnClickListener(this);    }    //初始化第一次点击的标记    long fristTime=0;    @Override    public void onClick(View v) {        if (fristTime == 0) {            fristTime = System.currentTimeMillis();//获取第一次点击的时间            new Thread() {                public void run() {                    try {                        Thread.sleep(500);                        fristTime = 0;//为双击做准备                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }.start();        } else {            long secondTime = System.currentTimeMillis();//获取第二次点击的时间            if (secondTime - fristTime < 500) {                System.out.println("我被双击了。。。");                fristTime = 0;//为下次双击做准备            }        }    }

三击:

同理,用上面这种方式也能实现三击,只是麻烦了些。
参考Google,安卓手机中在查看安卓系统版本的地方,三击或者多击会出现彩蛋,可以借鉴其源码进行实现。
 //利用数组来存储时间    long[] mHits = new long[3];    @Override    public void onClick(View v) {        // arraycopy 拷贝数组        /*  参数解读如下:         *  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.  拷贝的长度 */        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);        //获取离开机的时间        mHits[mHits.length - 1] = SystemClock.uptimeMillis();        //单击时间的间隔,以500毫秒为临界值        if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {            System.out.println("我被三击了。。。");            //一个三击(双击或多击事件完成),            //把数组置为空并重写初始化,为下一次三击(双击或多击)做准备            mHits = null;            mHits = new long[3];        }    }

多击:

我们只需把数组的长度进行相应的更改,例如,把 new long[3]中的3改为2 或者其它数字 ,即可实现双击或多击的功能。


2 0
原创粉丝点击