Android - Get keyboard key press

后端 未结 4 1738
独厮守ぢ
独厮守ぢ 2020-12-08 05:00

I want to catch the press of any key of the softkeyboard. I don\'t want a EditView or TextView in my Activity, the event must be handled from a extended View inside my Activ

相关标签:
4条回答
  • 2020-12-08 05:13

    When Keyboard is opened in activity your activity actually becomes foreground... All TextArea or TextFields have their own mechanism to get keypressed from onScreen keyboard... if you want to use onKeyDown() listner for virtual keyboard make sure that you set in AndroidManifest File under your activity android:windowSoftInputMode="stateAlwaysVisible" then onkeyDown() will work it did worked for me ...

    0 讨论(0)
  • 2020-12-08 05:19

    There are no option to handling key press events on soft keyboard (an on-screen keyboard) only from a hardware keyboard.

    for more details: Handling Keyboard Actions

    Note: When handling keyboard events with the KeyEvent class and related APIs, you should expect that such keyboard events come only from a hardware keyboard. You should never rely on receiving key events for any key on a soft input method (an on-screen keyboard).

    0 讨论(0)
  • 2020-12-08 05:20

    With the hint of vasart i can get the KeyPress event. To make the keycode printable i have used the function getUnicodeChar passing it the meta button state then just a char cast solve the problem.

    This is the working code:

    @Override
    public boolean dispatchKeyEvent(KeyEvent KEvent) 
    {
        int keyaction = KEvent.getAction();
    
        if(keyaction == KeyEvent.ACTION_DOWN)
        {
            int keycode = KEvent.getKeyCode();
            int keyunicode = KEvent.getUnicodeChar(KEvent.getMetaState() );
            char character = (char) keyunicode;
    
            System.out.println("DEBUG MESSAGE KEY=" + character + " KEYCODE=" +  keycode);
        }
    
    
        return super.dispatchKeyEvent(KEvent);
    }
    

    Of course this work only with ASCII character.

    0 讨论(0)
  • 2020-12-08 05:21

    For handling hardware keys and Back key you could use dispatchKeyEvent(KeyEvent event) in your Activity

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.i("key pressed", String.valueOf(event.getKeyCode()));
        return super.dispatchKeyEvent(event);
    }
    

    UPD: unfortunately you can't handle soft keyboard events (see Handle single key events), unless you develop your own custom keyboard (follow the link to learn how Creating input method).

    0 讨论(0)
提交回复
热议问题