How to listen for enter key in android edit text?

Viewed 392

How do you listen for an enter press (through the emulated device keyboard, not the computer keyboard) in android? I have tried many solutions including using an onEditorActionListener with various different IME actions, an onKeyListener for Action.DOWN or KeyEvent.KEYCODE_ENTER - and dozens of variations of the two.

Setting the edit text to a single line works, but I want the edittext to be multiline, and to still create a new line when enter is pressed. Several other answers work to varying degrees but none provide what I want: an android emulator keyboard enter key that functions normally (creates new line) but also can be listened to for triggering my own methods.

I know this question has been asked a plethora of times but none of the answers work in my code.

Here is my current bare bones code.

characterNotesEditText.setOnEditorActionListener { _, actionId, event ->
        Log.i("FragmentActivity", "It works")
        return@setOnEditorActionListener true
    }

It triggers the Log if enter is pressed on the laptop, but only triggers on the emulator keyboard if the enter key was pressed before. This works once, and then pressing enter on the emulator keyboard does nothing.

1 Answers

In the end I gave up using key listener or ime action listener and from CommonsWare's advice I used a textwatcher to track for new lines.

The following code was my final solution, the use case being to find when a new line is created, and to automatically indent it. The 'toDelete' boolean is used to make sure backspacing through the indents is possible.

 override fun beforeTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {
    val string: String = text.toString()
    toDelete = string.length > 1 && string[string.length - 2] == '\n'
}

override fun onTextChanged(
    txt: CharSequence,
    start: Int,
    before: Int,
    count: Int
) {
    if (!toDelete) {
        val string: String = txt.toString()
        if (string.isNotEmpty() && string[string.length - 1] == '\n') {
            if (editText.selectionStart == txt.length || editText.selectionEnd == txt.length) {
                editText.text.append("    ")
            }
        }
    }
}
Related