如何使用Kotlin

时间:2016-05-13 04:51:56

标签: 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;
    }
});

我设法得到了这个(我甚至不确定它是否正确):

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

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

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

5 个答案:

答案 0 :(得分:45)

当您的Kotlin lambda返回Boolean时,onEditorAction会返回Unit。将其更改为即:

editText.setOnEditorActionListener { v, actionId, event ->
      if(actionId == EditorInfo.IME_ACTION_DONE){
          doSomething()
          true
      } else {
          false
      }
}
关于lambda表达式和匿名函数的

The documentation是一个很好的阅读。

答案 1 :(得分:4)

Kotlin在 关键字时会很棒,而不是使用 if else

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

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

p / s:在lambda的右侧需要@Pier因代码而无法工作的代码。所以,我们必须使用true / false而不是return true / false

答案 2 :(得分:0)

您可以使用另一种形式:

i

答案 3 :(得分:0)

为EditText编写简单的Kotlin扩展

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

并使用它

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

答案 4 :(得分:0)

使用此代码:

et.setOnEditorActionListener { v, actionId, event ->
            when(actionId){
                EditorInfo.IME_ACTION_DONE -> {
                    Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show()

                true
            }

            EditorInfo.IME_ACTION_NEXT -> {
                Toast.makeText(this, "Next", Toast.LENGTH_SHORT).show()
                true
            }
            else -> false
        }
    }