我怎么可以创建一个单一的点击事件和双击事件时,菜单按钮是pressed? [英] How can I create a Single Click Event and Double Click Event when the Menu Button is pressed?

查看:134
本文介绍了我怎么可以创建一个单一的点击事件和双击事件时,菜单按钮是pressed?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检测到一个单一的点击或双击时,菜单按钮是pressed。如果一个单一的点击检测到有人甚至会发生,如果双击检测到不同的事件发生。这里是我试过(在发生的事件中使用吐司):

I want to be able to detect a single click or a double click when the menu button is pressed. If a single click is detected one even will happen, if a double click is detected a different event will happen. Here is what I've tried(Using toast in place of events):

private static final long DOUBLE_PRESS_INTERVAL = 250; // in millis
private long lastPressTime;

@Override
public boolean onPrepareOptionsMenu(Menu menu) {    

    // Get current time in nano seconds.
    long pressTime = System.currentTimeMillis();


    // If double click...
    if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
        Toast.makeText(getApplicationContext(), "Double Click Event", Toast.LENGTH_SHORT).show();
        return true;
    }

    // If not double click....
    Toast.makeText(getApplicationContext(), "Single Click Event", Toast.LENGTH_SHORT).show();

    // record the last time the menu button was pressed.
    lastPressTime = pressTime;      
    return true;
}

现在的问题是,一个单一的点击事件被检测到双击事件之前每一次。

The problem is that a single click event is detected every time before a double click event.

推荐答案

简单的逻辑错误。在录制新的最后pressTime之前返回。您应该只有一个返回呼叫,如果他们都返回了同样的事情:

Simple logic mistake. You are returning before recording the new lastPressTime. You should only have one return call if they are both returning the same thing:

boolean mHasDoubleClicked = false;

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {    

        // Get current time in nano seconds.
        long pressTime = System.currentTimeMillis();


        // If double click...
        if (pressTime - lastPressTime <= DOUBLE_PRESS_INTERVAL) {
            Toast.makeText(getApplicationContext(), "Double Click Event", Toast.LENGTH_SHORT).show();
            mHasDoubleClicked = true;
        }
        else {     // If not double click....
            mHasDoubleClicked = false;
            Handler myHandler = new Handler() {
                 public void handleMessage(Message m) {
                      if (!mHasDoubleClicked) {
                            Toast.makeText(getApplicationContext(), "Single Click Event", Toast.LENGTH_SHORT).show();
                      }
                 }
            };
            Message m = new Message();
            myHandler.sendMessageDelayed(m,DOUBLE_PRESS_INTERVAL);
        }
        // record the last time the menu button was pressed.
        lastPressTime = pressTime;      
        return true;
    }

这篇关于我怎么可以创建一个单一的点击事件和双击事件时,菜单按钮是pressed?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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