如何计算按钮释放后经过的时间?

时间:2015-10-02 14:26:06

标签: android time

我正在尝试制作一个简单的摩尔斯电码转换器。我可以计算用户按住一个按钮以制作点或短划线的时间,但是我在计算自用户释放按钮以来已经过的时间时遇到了麻烦 - 经过的时间将让我弄清楚是否它是一个新的字母/单词,通过计时符号之间的空格。

 public void btnPressed(View view)
   {
        button.setOnTouchListener(new View.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;

                //Timer starts when the button is released.
                start = System.currentTimeMillis();

            }
            return false;
        }
    });

    //This is where attempt to calculate the elapsed time.
    stop = System.currentTimeMillis() - start;

它确实返回一个时间 - 问题是经过的时间只有几毫秒长。有没有更简单的方法来解决这个问题?

2 个答案:

答案 0 :(得分:0)

你似乎对自己如何解决这个问题感到困惑 看来你的按钮onTouch处理程序中你已经设置了一个新的处理程序。这是一个容易出错的错误路径。

简单的方法是只有一个onTouch回调。

此按钮记录按钮停止和向上的时间。

@Override
public boolean onTouch(View v, MotionEvent event) {

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        // we have pressed, record the time
        pressTime = System.currentTimeMillis();

        // check how long it has been since last release
        timeSinceLastRelease = System.currentTimeMillis() - releaseTime;

    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        // we have released, record the time
        releaseTime = System.currentTimeMillis();

        // check how long it has been since last press
        timeSinceLastPress = System.currentTimeMillis() - pressTime;           
    }
    return false;
}

答案 1 :(得分:0)

将以下代码放在onCreate而不是btnPressed

button.setOnTouchListener(new View.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;

                //Timer starts when the button is released.
                start = System.currentTimeMillis();

            }
            return false;
        }

代码中发生的事情是touchListner仅在您点击按钮后才有效。将其放入onCreate将使其始终有效。