I have a Fragment that contains an Edit Text. When the Edit Text is pressed, the keyboard is being shown. When pressed the Save button in the upper corner, the application retur
For Kotlin, you can use this as a top level function, just add the code to a separate class such as Utils.kt
.
fun hideKeyboard(activity: Activity) {
val inputMethodManager =
activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
// Check if no view has focus
val currentFocusedView = activity.currentFocus
currentFocusedView?.let {
inputMethodManager.hideSoftInputFromWindow(
currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
To access it from Fragment, call it like:
hideKeyboard(activity as YourActivity)
Thanks to Silvia H for Java code.