Skip to content

Instantly share code, notes, and snippets.

@alextcn
Created January 9, 2019 20:16
Show Gist options
  • Save alextcn/3988fad62ab4532809c9da39ca50ee92 to your computer and use it in GitHub Desktop.
Save alextcn/3988fad62ab4532809c9da39ca50ee92 to your computer and use it in GitHub Desktop.
Listener for enter key input for EditText
/**
* Simple [TextView.OnEditorActionListener] implementation for handling IME action
* @param onAction called when IME action selected or Enter is clicked
*/
class EnterActionListener(private val onAction: () -> Unit) : TextView.OnEditorActionListener {
override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
// If triggered by an enter key, this is the event; otherwise, this is null.
// if shift key is down, then we want to insert the '\n' char in the TextView;
if (event == null || event.isShiftPressed) return false
onAction()
return true
}
}
fun TextView.setOnEnterActionListener(onAction: () -> Unit) =
this.setOnEditorActionListener(EnterActionListener(onAction))
// and use it like that
// editText.setOnEnterActionListener {
// Toast.makeText(context, "Click", Toast.LENGTH_SHORT).show()
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment