如何检测按钮时,pressed和释放的机器人 [英] How to detect when button pressed and released on android

查看:91
本文介绍了如何检测按钮时,pressed和释放的机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启动开始时一个按钮pssed第一$ P $结束时,它被释放(基本上我想衡量一个按钮的时间长短下降)的定时器。我将使用System.nanoTime()方法,在这两个时间,然后减去初始数量从最后一节以获取经过,而按钮被按住的时间的测量。

I would like to start a timer that begins when a button is first pressed and ends when it is released (basically I want to measure how long a button is held down). I'll be using the System.nanoTime() method at both of those times, then subtract the initial number from the final one to get a measurement for the time elapsed while the button was held down.

(如果您有使用其他的东西比nanoTime()或测量按钮的时间长短下来的一些其他的方式有什么建议,我是开放给那些为好。)

(If you have any suggestions for using something other than nanoTime() or some other way of measuring how long a button is held down, I'm open to those as well.)

谢谢! 刘德华

推荐答案

我觉得这样的事情应该工作:(主要用它代替OnClickListener OnTouchListener)

I think something like this should work: (basically use OnTouchListener instead of OnClickListener)

// this goes somewhere in your class:
  long lastDown;
  long lastDuration;

  ...

  // this goes wherever you setup your button listener:
  button.setOnTouchListener(new OnTouchListener() {
     @Override
     public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
           lastDown = System.currentTimeMillis();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
           lastDuration = System.currentTimeMillis() - lastDown;
        }
     }
  };

这篇关于如何检测按钮时,pressed和释放的机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆