检测长按“虚拟”后退键

时间:2011-12-04 19:32:37

标签: android

尚未找到解决方案。 我想检测长按“虚拟”后退键,例如你在星系s2找到的那个。

当用户按下按钮时,我试图检测onKeyDown事件(有效),当用户离开按钮时,我尝试检测onKeyUp事件,但虚拟键一直触发onKeyUp-events。

我也试图覆盖onKeyLongPress方法,但这没有帮助。

 @Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {
        mBackKeyDownTime = event.getEventTime();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        mBackKeyUpTime = event.getEventTime();
        final long delta = mBackKeyUpTime - mBackKeyDownTime;
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

1 个答案:

答案 0 :(得分:6)

试试这个...

    int LONG_PRESS_TIME = 5000; // Time in miliseconds
    Handler handler;
    Runnable longPressed;

    handler = new Handler();
    longPressed = new Runnable() {
    public void run() {
    Log.d("LogTag", "Long Pressed");
    }
};

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    if (keyCode == KeyEvent.KEYCODE_BACK)
     {
             handler.postDelayed(longPressed, LONG_PRESS_TIME);
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }

 @Override
 public boolean onKeyUp(int keyCode, KeyEvent event)
 {
     if(keyCode == KeyEvent.KEYCODE_BACK)
     {
         handler.removeCallbacks(longPressed);
         return true;
     }
     return super.onKeyUp(keyCode, event);
 }