Android SoftKeyBoard Enter Key Handling

How to Handle Android Keyboard’s Enter Key to Support your Own Function

By default, android soft keyboard’s enter key doesn’t support your own function even if you have set “imeOptions” in the xml of the layout. It is a useful thing if you can execute a function right from the keyboard enter key, for example, to initiate a search after typing search query or to send a chat message etc.

With some additional code, we can do it and here is a code example, just insert this code in the onCreate method.

Java code to handle soft keyboard enter button

In this example, there is an edittext field, after typing the text in it, the keyboard enter key will execute your function

myEditText.setOnKeyListener(new View.OnKeyListener() {
           public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                     if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                            (keyCode == KeyEvent.KEYCODE_ENTER)) {
                               //do your action here
                             
                               return true;
                              }
                      return false;
                      }
       });

 

Post navigation

Comments

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