0

When I press the back button on my Android phone it closes the soft keyboard, but when calling onbackpressed method it doesn't close the soft keyboard

I have tried to close the soft keyboard programmatically, but I could not solve the problem exactly

val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

    if (imm.isAcceptingText){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        android.R.id.accessibilityActionHideTooltip

    }*

I want to close the soft keyboard while calling the onbackpressed method, How exactly does the back button work in Android?

If I call the onbackpressed method I need to close the soft keyboard programmatically, I need to avoid that closing keyboard code

  • 2
    And for your other question calling `onBackPress()` will not close the keyboard because keyboard closing event on back button pressed is handled by system itself and consumed also. If you manually trigger `onBackPress()` it will not call that hiding piece of code.. – ADM Jun 13 '19 at 05:06

1 Answers1

1

This should close your keyboard

    window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)

or create a function

fun hideKeyboard(activity: Activity) {
    val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    //currently focused view
    var view = activity.currentFocus
    //If null, create a new one
    if (view == null) {
        view = View(activity)
    }
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

and call

    hideKeyboard(your_activity_context as YourActivity)
Ferran
  • 1,442
  • 1
  • 4
  • 10