Se você não quiser usar xml, faça uma extensão Kotlin para ocultar o teclado
// In onResume, call this
myView.hideKeyboard()
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
Alternativas baseadas no caso de uso:
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
// Calls Context.hideKeyboard
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
view.hideKeyboard()
}
Como mostrar o teclado virtual
fun Context.showKeyboard() { // Or View.showKeyboard()
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}
Método mais simples ao solicitar simultaneamente o foco em um edittext
myEdittext.focus()
fun View.focus() {
requestFocus()
showKeyboard()
}
Simplificação de bônus:
Remova os requisitos para sempre usar getSystemService
: Biblioteca Splitties
// Simplifies above solution to just
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
android:windowSoftInputMode="stateHidden"