1

I am trying to get the key pressed on soft keyboard but am unable to do so. Currently i am using the following 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);

}

It is catching key events for the hardware keyboard but not for the virtual one. Can someone help me out

Vaibhav
  • 703
  • 1
  • 7
  • 18
  • http://developer.android.com/reference/android/text/method/KeyListener.html Default android software keyboard won't trigger listener's methods at all. – mkrakhin Jan 20 '15 at 08:06

2 Answers2

4

From the Android Official Page

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).

So you should use TextWatcher Interface to observe the characters pressed on the SoftKeyboard, example:

myEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            // TODO Auto-generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {

            // TODO Auto-generated method stub
        }
    });
Sharp Edge
  • 4,144
  • 2
  • 27
  • 41
-1

This should be your solution:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 1) { 
        finish();
        return true; 
    }

    return super.onKeyDown(keyCode, event);
}
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
QArea
  • 4,955
  • 1
  • 12
  • 22