I am using the Android Jetpack Navigation Component for navigating between fragments back and forth. On one Fragment, I have a SearchView in expanded form. When I press the back button (to the left of the SearchView), then the following happens:
- the SearchView will be first closed instead of navigating to the previous screeen
- I need to press the back button a 2nd time to navigate to the previous screen
Why is that ? Why it does not navigate directly to the previous screen?
Here, you can see the code in the fragment handling the SearchView-related code:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// add a search view to the menu
inflater.inflate(R.menu.search_menu, menu)
val searchItem = menu.findItem(R.id.search)
searchView = searchItem.actionView as SearchView
searchItem.expandActionView()
searchView.apply {
queryHint = "Search"
isIconified = false
/* this shows the query the user has typed (no submission) so that the user can see which search query was used */
setQuery(args.query, false)
doOnLayout {
this.clearFocus()
}
setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String): Boolean {
// do some stuff with the query ..
return false
}
override fun onQueryTextChange(newText: String): Boolean = false
})
}
}
Here, you can see the search_menu.xml
file content:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- SearchView -->
<item android:id="@+id/search"
android:title="@string/search"
android:icon="@drawable/search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
<item android:id="@+id/profile_icon"
android:title="@string/profile"
android:icon="@drawable/account"
app:showAsAction="collapseActionView|ifRoom"/>
</menu>
What do I need to add to my code so that the app directly navigates back to the previous screen when I press the back button without closing the SearchView first ?