Search code examples
androidandroid-architecture-componentsandroid-architecture-navigation

How to make sure that back button for settings fragment goes to the launching fragment with aac


So I have an issue with AAC navigation. I have multiple fragments in one activity. I inflate the menu options in MainActivity so that each fragment has access to the menu item which opens the settings. The problem is that each time I press the back button on a fragment, it does not go back to the fragment that launched it. It goes back to the original fragment. Is there a way to make sure this behavior is assured? Thanks


Solution

  • If you are calling fragment by menu item id then do it in your activity like below.It will solve your problem.

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return NavigationUI.onNavDestinationSelected(item,navController) || super.onOptionsItemSelected(item)
    }
    

    And your menu item:

    <menu xmlns:android="http://schemas.android.com/apk/res/android" 
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
            android:id="@+id/settingsFragment"
            android:title="Settings"
            android:menuCategory="secondary"
            app:showAsAction="never" />
    

    MenuCategory = "secondary" will not pop out back stack to start destination.