Kotlin Solution
The direct way to handle the hide keyboard + done action in Kotlin is:
// Set action
edittext.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Hide Keyboard
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
true
}
false
}
Kotlin Extension
Use this to call edittext.onDone {/*action*/}
in your main code. Keeps it more readable and maintainable
edittext.onDone { edittext.hideKeyboard() }
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
fun EditText.onDone(callback: () -> Unit) {
// These lines optional if you don't want to set in Xml
imeOptions = EditorInfo.IME_ACTION_DONE
maxLines = 1
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
}
Additional Keyboard Extensions
If you'd like more ways to simplify working with the keyboard (show, close, focus): Read this post
Don't forget to add these options to your edittext Xml, if not in code
<EditText ...
android:imeOptions="actionDone"
android:inputType="text"/>
Need inputType="textMultiLine"
support? Read this post and don't add imeOptions
or inputType
in Xml