0

I'm currently struggling to combine navigation and closing the keyboard on button click. Right now I have a button which uses R.id.action.actionname to navigate to a new fragment. This is currently set in an onclick listener. If the user navigates to the new fragment, the keyboard stays open, which shouldn't be happening.

I've tried using the code below without success

 val inputManager =
            activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = this.activity!!.currentFocus
        binding.idLoginButton.setOnClickListener() {

            if (currentFocusedView != null) {
                inputManager.hideSoftInputFromWindow(
                    currentFocusedView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
            Navigation.createNavigateOnClickListener(R.id.action_homeFragment_to_loginFragment)
        }

I've also tried putting

Navigation.createNavigateOnClickListener(R.id.action_homeFragment_to_loginFragment)

between the brackets of

  binding.idLoginButton.setOnClickListener()

which also didn't work.

iCV
  • 407
  • 4
  • 18

2 Answers2

2

Put this code in Your Activity class :-

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    if (currentFocus != null) {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
    }
    return super.dispatchTouchEvent(ev)
}

And hope it will fix your problem.

Alok Mishra
  • 1,226
  • 10
  • 15
0

If there is no focused view (e.g. can happen if you just changed fragments), there are other views that will supply a useful window token.

These are alternatives for the above code if (view == null) view = new View(activity); These don't refer explicitly to your activity.

Inside a fragment class:

view = getView().getRootView().getWindowToken(); Given a fragment fragment as a parameter:

view = fragment.getView().getRootView().getWindowToken(); Starting from your content body:

view = findViewById(android.R.id.content).getRootView().getWindowToken();

And also add this line to the end of the method:

view.clearFocus();

For more: https://stackoverflow.com/a/17789187/9351811

Kuvonchbek Yakubov
  • 157
  • 1
  • 2
  • 10