How to setOnEditorActionListener with Kotlin

Kotlin would be great with when keyword instead of using if else

To me, the following code is more pretty:

editText.setOnEditorActionListener() { v, actionId, event ->
  when(actionId)){
      EditorInfo.IME_ACTION_DONE -> { doSomething(); true }
      else -> false
  }
}

p/s: The code of @Pier not working because of a expression is required on the right side of lambda. So, we have to use true/false instead of return true/false


Write simple Kotlin extention for EditText

fun EditText.onAction(action: Int, runAction: () -> Unit) {
    this.setOnEditorActionListener { v, actionId, event ->
        return@setOnEditorActionListener when (actionId) {
            action -> {
                runAction.invoke()
                true
            }
            else -> false
        }
    }
}

and use it

/**
 * use EditorInfo.IME_ACTION_DONE constant
 * or something another from
 * @see android.view.inputmethod.EditorInfo
 */
edit_name.onAction(EditorInfo.IME_ACTION_DONE) {
  // code here
}


The onEditorAction returns a Boolean while your Kotlin lambda returns Unit. Change it to i.e:

editText.setOnEditorActionListener { v, actionId, event ->
      if(actionId == EditorInfo.IME_ACTION_DONE){
          doSomething()
          true
      } else {
          false
      }
}

The documentation on lambda expressions and anonymous functions is a good read.

Tags:

Android

Kotlin