I'm trying to write a simple Android app in Kotlin. I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard.
There is a popular question Close/hide the Android Soft Keyboard about doing it in Java, but as far as I understand, there should be an alternative version for Kotlin. How should I do it?
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your edit field. This will force the keyboard to be hidden in all situations.
Ok everyone knows that to hide a keyboard you need to implement: InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm. hideSoftInputFromWindow(getCurrentFocus(). getWindowToken(), 0);
Tap the back button on your Android. It's the left-pointing arrow button at the bottom of the screen, either at the bottom-left or bottom-right corner. The keyboard is now hidden.
Use the following utility functions within your Activities, Fragments to hide the soft keyboard.
(*)Update for the latest Kotlin version
fun Fragment.hideKeyboard() { view?.let { activity?.hideKeyboard(it) } } fun Activity.hideKeyboard() { hideKeyboard(currentFocus ?: View(this)) } fun Context.hideKeyboard(view: View) { val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0) }
This will close the keyboard regardless of your code either in dialog fragment and/or activity etc.
Usage in Activity/Fragment:
hideKeyboard()
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