Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close/hide the Android Soft Keyboard with Kotlin

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?

like image 935
Eugene Trifonov Avatar asked Jan 22 '17 11:01

Eugene Trifonov


People also ask

How do you close hide the Android soft keyboard?

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.

How do I hide the soft keyboard on Android after clicking outside EditText Kotlin?

Ok everyone knows that to hide a keyboard you need to implement: InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); imm. hideSoftInputFromWindow(getCurrentFocus(). getWindowToken(), 0);

How do I collapse my Android keyboard?

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.


1 Answers

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() 
like image 78
Gunhan Avatar answered Sep 21 '22 05:09

Gunhan