4

How to catch onKeyLongPress on KeyboardKey. The code below works only if I put "KEYCODE_VOLUME_DOWN" or "KEYCODE_VOLUME_UP" instead of "KEYCODE_Q". I also tried to write "113" instead of "KeyEvent.KEYCODE_Q", but it didn't help.

(If you need the XML please ask.)

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_Q) {
        shortPress = false;
        Toast.makeText(this, "longPress", Toast.LENGTH_SHORT).show();
        return true;
    }

    return false;
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_Q) {
        if(event.getAction() == KeyEvent.ACTION_DOWN){
            event.startTracking();
            if(event.getRepeatCount() == 0){
                shortPress = true;
            }
            return true;
        }
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_G) {
        if(shortPress){
            Toast.makeText(this, "shortPress", Toast.LENGTH_SHORT).show();
        }
        
        shortPress = false;

        return true;
    }

    return super.onKeyUp(keyCode, event);
}
Mahm00d
  • 3,881
  • 8
  • 44
  • 83
jelic98
  • 723
  • 1
  • 12
  • 28
  • I think onKeyLongPress method works only on hardware keys not software keyboard. Are you using hardware keyboard? – krystian71115 Jun 28 '15 at 20:25
  • No, I am developing my own soft keyboard. Can you tell me how to detect longpress on KeyboardKey. Thanks in advace. – jelic98 Jun 28 '15 at 22:03
  • 1
    If you're developing a keyboard, you won't get incoming keyboard events. You're generating keyboard events. Touches on keys would be found from touches on your view. – Gabe Sechan Jul 01 '15 at 00:13
  • Hmm ok. That is right but I still cant sleep because my keyboard cant detect longpress on keys. Can you tell me how to detect longpress on every single button without coordinates of my view and that stuff? Thanks for reply. – jelic98 Jul 01 '15 at 06:28

2 Answers2

3

For soft keyboard, you should use proper timer to handle long press event like any other applications. LatinIME also uses this solution, please check out.

PointerTracker.onDownEventInternal.startLongPressTimer()

Hitchhiker
  • 99
  • 5
1

My solution for long press on the space key.

private long ms_press;
...
@Override
public void onPress( int i ){
    ms_press = System.currentTimeMillis();
}
...
@Override
public void onKey( int primaryCode, int[] keyCodes) {
    if( primaryCode == 32 && (System.currentTimeMillis()-ms_press) >= 1000  ){ 
        //long press on Space key
    }else{
        //...
    }
}
Style-7
  • 985
  • 12
  • 27