Search code examples
androidandroid-softkeyboard

Android - onBackPressed close soft keyboard AND activity


I have an activity only for the SearchView which is focused on created so the soft keyboard pops up.

This is the code (kotlin):

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_search_input)

    searchInput.isIconified = false

    searchInputLayout.setOnClickListener {
        finish()
    }
}


override fun onBackPressed() {
    searchInput.clearFocus()
    finish()
}

As you can see I try to close the activity when back button is pressed but it only closes the soft keyboard.

How can I do this??

Thanks in advance


Solution

  • You can create customized view and implement onKeyPreIme(keyCode: Int, event: KeyEvent) and check for keyCode == KeyEvent.KEYCODE_BACK event.

    Hope this answer will explain it to you furthermore.

    Edited:

    try to implement these for your SearchView:

    searchInput.setOnQueryTextFocusChangeListener{ _, b->
        if(!b){
         searchview.isIconified = true
         finish()
       }
    }