Handling Enter Key on EditText (Kotlin, Android)
Solution 1:
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
})
Solution 2:
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
}
}