Use "ENTER" key on softkeyboard instead of clicking button

Peter O. picture Peter O. · Dec 15, 2010 · Viewed 126.4k times · Source

Hello I've got a searched EditText and search Button. When I type the searched text, I'd like to use ENTER key on softkeyboard instead of search Button to activate search function.

Thanks for help in advance.

Answer

Julian picture Julian · Dec 15, 2010

You do it by setting a OnKeyListener on your EditText.

Here is a sample from my own code. I have an EditText named addCourseText, which will call the function addCourseFromTextBox when either the enter key or the d-pad is clicked.

addCourseText = (EditText) findViewById(R.id.clEtAddCourse);
addCourseText.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    addCourseFromTextBox();
                    return true;
                default:
                    break;
            }
        }
        return false;
    }
});