Search code examples
androidandroid-softkeyboard

Android: how to make keyboard enter button say "Search" and handle its click?


I can't figure this out. Some apps have an EditText (textbox) with the help of which, when you touch it and it brings up the on-screen keyboard, the keyboard has a "Search" button instead of an enter key.

I want to implement this. How can I implement that Search button and detect the press of the Search button?

Edit: found how to implement the Search button; in XML, android:imeOptions="actionSearch" or in Java, EditTextSample.setImeOptions(EditorInfo.IME_ACTION_SEARCH);. But how do I handle the user pressing that Search button? Does it have something to do with android:imeActionId?


Solution

  • In the layout set your input method options to search.

    <EditText
        android:imeOptions="actionSearch" 
        android:inputType="text" />
    

    In the java add the editor action listener.

    editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        }
    });
    

    In kotlin use below:

     editText.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
              performSearch()
            }
            true
          }