如何使用Kotlin设置OnEditorActionListener
所以我有这个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中编写这样的事件处理程序呢?
当你的Kotlin lambda返回Unit
时, onEditorAction
返回一个Boolean
。 把它改成ie:
editText.setOnEditorActionListener() { v, actionId, event -> if(actionId == EditorInfo.IME_ACTION_DONE){ doSomething() true } else { false } }
lambda表达式和匿名函数的文档是一个很好的阅读。
当关键字不是使用时, Kotlin会很棒
对我来说,下面的代码更加漂亮:
editText.setOnEditorActionListener() { v, actionId, event -> when(actionId)){ EditorInfo.IME_ACTION_DONE -> doSomething(); true else -> false } }
p / s:由于表达式的@Pier代码不工作,所以需要在lambda的右侧。 所以,我们必须使用true / false而不是返回true / false