I am loading a Fragment while using Navigation component with this code and it works.
findNavController().navigate(R.id.menu_nav_graph, bundleOf("menuItem" to item))
I want to close the Fragment on button click and I use this code for that
findNavController().popBackStack()
The app navigates to the previous fragment but when I try to navigate to the popped Fragment destination again with the code above the app reaches the code and nothing happens. The Fragment is not loading. So the navigation code is executed but the Fragment is not opening. The same happens when instead of using popBackStack I use this with the onClick listener
activity?.onBackPressed()
Same effect, the app reaches the navigation line, no crash, no exception is thrown, it just doesn't open the Fragment.
At the same time, my back arrow navigation is working and it does go to the same destination multiple times after pressing back from the Fragment. This confuses me as I am using the same code in onOptionsItemSelectedand it works, so I don't understand what makes it different when I just call onBackPressed() on button click.
override fun onOptionsItemSelected(item: MenuItem): Boolean =
when (item.itemId) {
android.R.id.home -> {
activity?.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
How to close a Fragment on button click and be able to navigate to the same destination consequently?