Search code examples
androidkotlinandroid-fragmentsandroid-jetpack-navigation

Jetpack Navigation: Any fragment should be able to navigate to any fragment


I have a game flow where the user goes through 6 fragments in a row. Now some complexity has been added. It is possible that each fragment can be reached by each fragment. It depends on what the players answer...

The good thing is, no backstack is needed. I.e. once I am in a fragment, I can't go back.

Anyway, I could now connect any fragment to any fragment in the nav_graph by xml with <action>. However, this makes my nav_graph very cluttered and I have a lot of redundant navigation code. Additionally, this solution scales very difficult. What do I do if I suddenly have 10 fragments?

What I want to write a function like goToNextFragment, which could be located in the associated Activity for example. So if needed, each fragment can call activity.goToNextFragment() and the navigation will be executed accordingly. Unfortunately, I can't find an approach to do this. I could of course initialize the new fragment on the nav_graph as host. But this seems strange to me and will probably break the transition.

Does anyone have an idea that could help me?


Solution

  • I think global actions can help solve your problem. You can put them on the same level as the fragments in the navigation graph. At least the navigation graph would be less cluttered

    Example:

    <navigation xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        
        <fragment
            android:id="@+id/coolFragment"
         ...
        />
         
        <action
            android:id="@+id/coolFragmentAction"
            app:destination="@id/coolFragment" />
    </navigation>
    
    

    You can read more about it here: https://developer.android.com/guide/navigation/navigation-global-action