如何使用Kotlin setOnEditorActionListener

Pie*_*ier 26 android kotlin

所以我有这个Java代码:

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

我已经设法得到这个(我甚至不确定它是正确的方式):

editText.setOnEditorActionListener() { v, actionId, event ->
      if(actionId == EditorInfo.IME_ACTION_DONE){
          doSomething()
      } else {
      }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误 Error:(26, 8) Type mismatch: inferred type is kotlin.Unit but kotlin.Boolean was expected

那么这样的事件处理程序是如何用Kotlin编写的?

mie*_*sol 51

onEditorAction回报Boolean,而你的科特林拉姆达的回报Unit.将其更改为ie:

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

关于lambda表达式和匿名函数的文档是一个很好的阅读.


小智 5

Kotlin最好使用when关键字,而不要使用if关键字

对我来说,以下代码更漂亮:

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

p / s:在lambda的右侧,由于表达式,@ Pier的代码不起作用。因此,我们必须使用true / false而不是返回true / false


小智 5

为 EditText 编写简单的 Kotlin 扩展

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

并使用它

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

Run Code Online (Sandbox Code Playgroud)