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 Activity.
I just tried this:
1) Override the onKeyUp(int keyCode, KeyEvent event)
Activity method. This don't work with softkeybord it just catch few hardkeyboard.
2) Create my OnKeyListener
and register that in my View that contains a registered and working OnTouchListener
. This not work at all with softkeyboar.
3) Override the onKeyUp(int keyCode, KeyEvent event)
View method. This not work at all niether if i set my OnKeyListener nor if i don't set it.
4) With the InputMethodManager
object Call the method showSoftInput
and passing it my View. This don't work neither for raise up the keyboard, indeed i have to call toggleSoftInput
; nor to catch the key events.
I tested all only in the emulator but i think it's enough. Why it's so complicate take a simple key event from a keyboard ?
Try using dispatchKeyEvent(KeyEvent event)
in your Activity
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
Log.i("key pressed", String.valueOf(event.getKeyCode()));
return super.dispatchKeyEvent(event);
}
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.
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
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 ...