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?
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.
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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With