2011-12-04 47 views
2

尚未找到解決方案。 我想檢測一個長按「虛擬」後退鍵,例如你在銀河系s2上找到的那個。檢測長按「虛擬」鑰匙

我試着檢測用戶按下按鈕時的onKeyDown事件(工作)和用戶離開按鈕時的onKeyUp事件,但虛擬按鍵始終觸發onKeyUp事件。

我也試着重寫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

你能後的代碼,你試過? – 500865

回答

5

嘗試用這種...

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); 
}