您的位置:首页 > 移动开发 > Android开发

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

2016-01-14 17:25 465 查看

双击:

先来看简单的实现方式

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 或者其它数字 ,即可实现双击或多击的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: