Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Enter Key on EditText (Kotlin, Android)

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

like image 376
Shekh Shagar Avatar asked Nov 15 '17 03:11

Shekh Shagar


3 Answers

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
            })
like image 120
Shekh Shagar Avatar answered Nov 07 '22 13:11

Shekh Shagar


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
        }


    }
like image 25
Tonnie Avatar answered Nov 07 '22 13:11

Tonnie


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.
     */
like image 3
F.Mysir Avatar answered Nov 07 '22 13:11

F.Mysir