Handling Enter Key on EditText (Kotlin, Android)
Asked Answered
R

4

26

How to handle Enter Key on EditText in Android Kotlin Language?

Rima answered 15/11, 2017 at 3:37 Comment(0)
R
59

Bellow is the simplest solution for above question

    editText.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {
                    //Perform Code 
                    return@OnKeyListener true
                }
                false
            })
Rima answered 15/11, 2017 at 3:37 Comment(3)
Make sure to check whether the action is down or up so you don't get duplicates. if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP)Delrosario
Thanks for your feedback.Rima
i used return@OnKeyListener false to hide keyboard after perfoming actionsAdsorbate
W
4

I used the when-expression to check if the enter-button was clicked

edittext.setOnKeyListener { v, keyCode, event ->
        
        when {

            //Check if it is the Enter-Key,      Check if the Enter Key was pressed down
            ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.action == KeyEvent.ACTION_DOWN)) -> {
                
                
                //perform an action here e.g. a send message button click
                sendButton.performClick()

                //return true
                return@setOnKeyListener true
            }
            else -> false
        }


    }
Wycoff answered 20/10, 2020 at 7:13 Comment(0)
R
3

This code handles both hardware and software enter key

Step 1 [Important] Specify in XML two attributes:

  1. android:imeOptions in order to show the user the correct button to press
  2. android:inputType in order to tell the user what text he has to input, numbers text etc

Step 2 Add in your Kotlin file:

yourEditText.setOnEditorActionListener { _, keyCode, event ->
        if (((event?.action ?: -1) == KeyEvent.ACTION_DOWN)
          || keyCode == EditorInfo.IME_PUT_THE_ACTION_YOU_HAVE_SET_UP_IN_STEP_1) {
          
             // Your code here

            return@setOnEditorActionListener true
        }
        return@setOnEditorActionListener false
}

The reason I choose setOnEditorActionListener is because it handles better this action. According to Docs:

   /**
     * Set a special listener to be called when an action is performed
     * on the text view.  This will be called when the enter key is pressed,
     * or when an action supplied to the IME is selected by the user.  Setting
     * this means that the normal hard key event will not insert a newline
     * into the text view, even if it is multi-line; holding down the ALT
     * modifier will, however, allow the user to insert a newline character.
     */
Regent answered 4/12, 2020 at 9:16 Comment(0)
U
0

I've created a very general solution for this:

        private val DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT =
            arrayListOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)
        private val DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT =
            arrayListOf(
                EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH,
                EditorInfo.IME_ACTION_DONE
            )

        @JvmOverloads
        fun EditText.setOnDoneListener(
            function: Runnable?, onKeyListener: View.OnKeyListener? = null,
            onEditorActionListener: TextView.OnEditorActionListener? = null,
            actionsToHandle: Collection<Int> = DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT,
            keysToHandle: Collection<Int> = DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT
        ) {
            //    Log.d("AppLog", "setOnDoneListener caller:${Thread.currentThread().stackTrace[4]}")
            setOnEditorActionListener { v, actionId, event ->
                if (onEditorActionListener?.onEditorAction(v, actionId, event) == true)
                    return@setOnEditorActionListener true
                if (actionsToHandle.contains(actionId)) {
                    function?.run()
                    return@setOnEditorActionListener function != null
                }
                return@setOnEditorActionListener false
            }
            setOnKeyListener { v, keyCode, event ->
                if (onKeyListener?.onKey(v, keyCode, event) == true)
                    return@setOnKeyListener true
                if (event.action == KeyEvent.ACTION_DOWN && keysToHandle.contains(keyCode)) {
                    function?.run()
                    return@setOnKeyListener function != null
                }
                return@setOnKeyListener false
            }
        }
Unexampled answered 22/5, 2022 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.