所以我有这个 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 is expected
那么这样的事件处理程序是如何用 Kotlin 编写的呢?
最佳答案
onEditorAction
返回 Boolean
而您的 Kotlin lambda 返回 Unit
。将其更改为即:
editText.setOnEditorActionListener { v, actionId, event ->
if(actionId == EditorInfo.IME_ACTION_DONE){
doSomething()
true
} else {
false
}
}
The documentation关于 lambda 表达式和匿名函数是一本不错的读物。
关于android - 如何使用 Kotlin 设置 OnEditorActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37201504/