Search code examples
androidandroid-jetpackandroid-architecture-navigation

How to display back button when navigating to self with navigation component?


I have set up my navigation bar like this

with(ActivityHolderBinding.inflate(layoutInflater)) {
        setContentView(root)
        val fragment = supportFragmentManager.findFragmentByTag("holder") as NavHostFragment
        toolbar.setupWithNavController(fragment.navController,AppBarConfiguration(fragment.navController.graph))
        setSupportActionBar(toolbar)
    }

But this only shows a back button when I navigate to another fragment and not when I navigate to self on the fragment marked as start destination.


Solution

  • As per this issue:

    setupActionBarWithNavController uses the current destination ID to determine if the Up button is shown, so the behavior you're seeing is working as intended.

    You can have multiple destinations that use the same Fragment class, so just create a separate destination for recursive calls:

    <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"
        android:id="@+id/catalog_nav_graph"
        app:startDestination="@id/categories">
    
        <fragment
            android:id="@+id/categories"
            android:name="somepackage.categories.CategoryListFragment"
            tools:layout="@layout/catalog_category_list_frag">
    
            <action
                android:id="@+id/action_category_to_category"
                app:destination="@id/categoriesRecursive" />
    
            <action
                android:id="@+id/action_category_to_product_list"
                app:destination="@id/products_frag" />
    
            <argument
                android:name="categoryId"
                app:argType="integer"
                android:defaultValue="0" />
    
        </fragment>
        <fragment
            android:id="@+id/categoriesRecursive"
            android:name="somepackage.categories.CategoryListFragment"
            tools:layout="@layout/catalog_category_list_frag">
    
            <action
                android:id="@+id/action_category_to_category"
                app:destination="@id/categoriesRecursive" />
    
            <action
                android:id="@+id/action_category_to_product_list"
                app:destination="@id/products_frag" />
    
            <argument
                android:name="categoryId"
                app:argType="integer"
                android:defaultValue="0" />
    
        </fragment>
        ....
    </navigation>
    

    So by having two different IDs, it is possible for NavigationUI to distinguish between your first level (which should not display an up arrow) vs ones that should display an up arrow.