close/hide the soft keyboard android kotlin


created a static utility method which can do the job VERY solidly, provided you call it from an Activity.
public static void hideKeyboard(Activity activity) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); //Find the currently focused view, so we can grab the correct window token from it. View view = activity.getCurrentFocus(); //If no view currently has focus, create a new one, just so we can grab a window token from it if (view == null) { view = new View(activity); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.
// Check if no view has focus: View view = this.getCurrentFocus(); if (view != null) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); }
This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).
Note: If you want to do this in Kotlin, use:context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
Kotlin Syntax
// Check if no view has focus: val view = this.currentFocus view?.let { v -> val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager imm?.let { it.hideSoftInputFromWindow(v.windowToken, 0) } }

No comments:

Post a Comment

Popular Posts