Rainmaker
Rainmaker

Reputation: 11100

Navigation popBackStack disables further navigation to this Fragment

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?

Upvotes: 3

Views: 1314

Answers (1)

Rainmaker
Rainmaker

Reputation: 11100

After debugging more I found out the root cause, the issue is not with the navigation not executing navigation but I guess with Fragment lifecycle in the navigation library implementation. The Fragment was not destroyed when backing off and the onBackPressed was triggered right after navigating to the same destination again.

To trigger onBackPressed I am using LiveData pushing this command from ViewModel. When returning to the Fragment the same command was pushed again to LiveData and the navigation back was triggered again so it appeared that no navigation was happening.

The solution was implementing SingleLiveEvent LiveData. It was pushing the value only once.

Here is the link to the implementation https://github.com/android/architecture-samples/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java

Upvotes: 5

Related Questions