Skip to content Skip to sidebar Skip to footer

Android - Getting Soft Keyboard Key Presses

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) { in

Solution 1:

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
        }
    });

Solution 2:

This should be your solution:

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

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

    return super.onKeyDown(keyCode, event);
}

Post a Comment for "Android - Getting Soft Keyboard Key Presses"