jane
jane

Reputation: 124

back pressing closes app even though keyboard is open

I have a searchView view in my activity. When i click on it, the keyboard opens (as it should) but when I press the back button I want it to close the keyboard (which is visible) but it closes the whole app. this started to happen after I added this code. This helps me to hide the keyboard when I touch outside of the keyboard:

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

What can I do so that pressing the back button first closes the open keyboard and only after that closes the app?

Upvotes: 0

Views: 102

Answers (1)

pykereaper
pykereaper

Reputation: 139

Are you sure that code snipped is causing the described behavior? I just wrote a small sample app to replicate the issue. However, even with your dispatchTouchEvent code, the first back button press just closes the keyboard and only the second one exits the app.

I tested it with an emulator on API 30.

Have you per change also overwritten onBackPressed() and/or onKeyDown()?

Edit:

I think I've found the problem and why it was working for me, but not for you.

  • First difference: You are using gesture navigation. If you switch to the 3-button navigation, I bet it will work for you, too.
  • Second difference (likely): When using SearchView, I could see the same behavior as you described/showed in the video. Switch to androidx.appcompat.widget.SearchView and the problem should be solved. :)

Upvotes: 1

Related Questions