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

双击:

先来看简单的实现方式

   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 或者其它数字 ,即可实现双击或多击的功能。


  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值