Si vous ne voulez pas utiliser XML, créez une extension Kotlin pour masquer le clavier
// Dans onResume, appelez ceci
myView.hideKeyboard()
fun View.hideKeyboard() {
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}
Alternatives basées sur le cas d'utilisation:
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun Activity.hideKeyboard() {
// Appelle Context.hideKeyboard
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
view.hideKeyboard()
}
Comment afficher le clavier virtuel
fun Context.showKeyboard() { // Ou View.showKeyboard()
val inputMethodManager = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInput(SHOW_FORCED, HIDE_IMPLICIT_ONLY)
}
Méthode plus simple lors de la demande simultanée de focus sur un EditText
myEdittext.focus()
fun View.focus() {
requestFocus()
showKeyboard()
}
Simplification en bonus:
Supprimez le besoin d'utiliser getSystemService
à jamais: Bibliothèque Splitties
// Simplifie la solution ci-dessus à juste
inputMethodManager.hideSoftInputFromWindow(windowToken, 0)