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?
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
dispatchTouchEventcode, 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/oronKeyDown()?Edit:
I think I've found the problem and why it was working for me, but not for you.
SearchView, I could see the same behavior as you described/showed in the video. Switch toandroidx.appcompat.widget.SearchViewand the problem should be solved. :)