7

Well, I'm trying to prevent the soft keyboard from closing when the user press the "ok" button after editing a text field. Actually, what i'm trying to achieve is : when "ok" button is pressed, the field is parsed and if valid, it starts another activity. That is easy enough.

But, when the field is not valid, I want the soft keyboard to stay open. And that's... a hell more complicated. If anyone know how to achieve such a thing...

Thanks in advance.

EDIT : what I mean by the OK button is the OK button from the soft keyboard.

Redwarp
  • 3,221
  • 3
  • 31
  • 44

1 Answers1

13

Attach OnEditorActionListener to your text field and return true from its onEditorAction method, when actionId is equal to IME_ACTION_DONE. This will prevent soft keyboard from hiding:

EditText txtEdit = (EditText) findViewById(R.id.txtEdit);
txtEdit.setOnEditorActionListener(new OnEditorActionListener() {

  public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
      // your additional processing... 
      return true;
    } else {
      return false;
    }
  }

});
Volo
  • 28,673
  • 12
  • 97
  • 125
  • 1
    Depending on your EditText `android:imeOptions` value, you may need to check actionId against `IME_NULL`, `IME_ACTION_GO` etc. – Volo Aug 29 '11 at 22:34
  • Worked perfectly! been looking for this. – zeitue Feb 11 '12 at 07:50
  • Thanks for the heads up @Idolon. My actionId == 66, but I couldn't find this constant in the EditorInfo class. – MrUser May 25 '14 at 18:42
  • That will not work not on newer versions of android nor on emulator – AlwaysConfused Oct 23 '17 at 21:39
  • @AlwaysConfused no wonder, it has been over 6 year since I posted this answer :). But thanks, for letting me know - I will check what was changed in the latest versions and update the answer accordingly. – Volo Oct 23 '17 at 22:29
  • @Idolon Hi, do you have any clue on how to keep the keyboard on? I couldn't find the "new" way. – Seeven Jul 10 '18 at 10:09