1

I have been trying to capture the Enter key for the past couple of hours but I donot get a call in the Listener. I am trying to provide a "Press Enter to send". But am always registering for the OnKeyListener. A few keys get called but randomly.

Its not a duplicate, since all the answers provide the same set of details, and this is a standard code. I am using the nexus 6P

My Code:

public void onCreate(){
        //set press enter to save state
        anEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
               if( keyCode ==
                        EditorInfo.IME_ACTION_SEND || event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                   if (new SharedPrefsManager(mContext).getBoolean(StringConstants.KEY_PRESS_ENTER_TO_SAVE, false)) {
                       Toast.makeText(mContext, "Enter pressed, to save", Toast.LENGTH_SHORT).show();
                   }
                   return true;
               }
                return false;
            }
        });
}

@OnCheckedChanged(R.id.check_enter_to_send)
public void enterToSendChecBoxClicked(CompoundButton buttonView, boolean isChecked){
    // 1. set the preference
    new SharedPrefsManager(mContext).putBoolean(StringConstants.KEY_PRESS_ENTER_TO_SAVE, isChecked);
}
ichthyocentaurs
  • 2,173
  • 21
  • 35

1 Answers1

3

There are no API for handling keyboard events on soft keyboard, only for hardware keyboard.

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

phnmnn
  • 12,813
  • 11
  • 47
  • 64