How to trigger a button click on press of the ‘DONE’/’ENTER’ key on Keyboard? [SOLVED]

Let’s say you have a form that asks the user to enter their name and age. And there is a submit button below the form, as shown below.

But sometimes this button could get hidden by the keyboard that popped up. So the user would have to hit the ‘back’ key to hide the keyboard and then click on your ‘Submit’ button. This doesn’t seem very user friendly.

Fortunately, Android’s Form keyboard now can be modified to have a ‘Done/ Go’ key instead of the usual ‘Enter’ key. You must have already noticed it in a lot places.

So let’s say you have an EditText and what you need to do is trigger the click on the submit button whenever the user presses the ‘Done/Go’ or ‘Enter’.
It’s pretty basic to achieve this. Just add the following code which is a special listener for EditText:

edittext.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
               //do what you want on the press of 'done'
               submit.performClick();
            }    
            return false;
        }
    });

In the above code the ‘edittext’ is an EditText object and ‘submit’ is the button object.
You will need to have the defined in your code.

EditText edittext=(EditText)findViewById(R.id.form);
Button submit=(Button)findViewById(R.id.submit);

 

If you want to replace the ‘Enter’ key with the ‘Done’ key then just add the following line to the xml file inside your

android:imeOptions="actionDone"

Reference:
http://stackoverflow.com/questions/9596010/android-use-done-button-on-keyboard-to-click-button

[wpedon id="7041" align="center"]

One thought on “How to trigger a button click on press of the ‘DONE’/’ENTER’ key on Keyboard? [SOLVED]

  1. Very informative and it works fine! Do you know how to solve this in a webbview? setOnEditorActionListener is not available for the WebView class.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.