Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setOnEditorActionListener with Kotlin

Tags:

android

kotlin

So I have this Java code:

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            doSomething();
            return true;
        }
        return false;
    }
});

I've managed to get this (which I'm not even sure it's the right way):

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

But I get an error Error:(26, 8) Type mismatch: inferred type is kotlin.Unit but kotlin.Boolean was expected

So how is such event handler written in Kotlin?

like image 315
Pier Avatar asked May 13 '16 04:05

Pier


3 Answers

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.

like image 151
miensol Avatar answered Nov 17 '22 15:11

miensol


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

like image 44
topcbl Avatar answered Nov 17 '22 16:11

topcbl


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
}

like image 5
Zaydel Eduard Avatar answered Nov 17 '22 16:11

Zaydel Eduard