Android Quick Tip
Close the keyboard when you click ‘DONE’… seems like a simple task, right? Unfortunately, clicking ‘DONE’ or the ‘RETURN’ button in even a single line Android EditText will not drop focus and close the soft keyboard. In most cases it will just generate a new line of text. So what do you have to do if you want to close the soft keyboard by clicking ‘DONE’?
First you need to set the android:imeOptions attribute equal to “actionDone” for your target EditText as seen below. That will change your ‘RETURN’ button in your EditText’s soft keyboard to a ‘DONE’ button.
1 2 3 4 5 6 7
Now we need to create a custom OnEditorActionListener for the target EditText that will recognize when the ‘DONE’ button has been clicked. In it we override the onEditorAction() method, get an instance of the InputMethodManager, and use it to close the soft keyboard. Here’s the code for the custom OnEditorActionListener class:
1 2 3 4 5 6 7 8 9 10 11
Now go to the onCreate() method of the Activity that contains the target EditText. We’ll call it SampleActivity here. In here you will assign the new DoneOnEditorActionListener to the target EditText via the setOnEditorActionListener() method.
1 2 3 4 5 6 7 8 9 10 11 12
And there you go, your target EditText field will now close the soft keyboard whenever you click the ‘DONE’ button. Very handy and not too difficult. Enjoy.