How to differentiate between long key press and regular key press?

前端 未结 3 1707
庸人自扰
庸人自扰 2020-12-16 01:46

I\'m trying to override the functionality of the back key press. When the user presses it once, I want it to come back to the previous screen. However, when the back key is

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 02:35

    I think the best way to handle it is as such.

    The only downside I can see here, is that single clicking the menu button doesn't make a sound in case the user has it enabled. Maybe there is a way to check this setting and use it, or call the default behavior.

    Code:

    private boolean _handledMenuButton=false;
    
    @Override
    public boolean onKeyUp(final int keyCode,final KeyEvent event) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_MENU:
              if (!_handledMenuButton) {
                  //Handle single clicking here
              }
              _handledMenuButton=false;
              return true;
        }
        return super.onKeyUp(keyCode,event);
    }
    
    @Override
    public boolean onKeyLongPress(final int keyCode, final KeyEvent event) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_MENU:
              //Handle long clicking here
              _handledMenuButton=true;
              return true;
        }
        return super.onKeyLongPress(keyCode,event);
    }
    
    @Override
    public boolean onKeyDown(final int keyCode,final KeyEvent event) {
        switch(keyCode) {
            case KeyEvent.KEYCODE_MENU:
                _handledMenuButton=false;
                event.startTracking();
                return true;
        }
        return super.onKeyDown(keyCode,event);
    }
    

提交回复
热议问题