Search code examples
androidmenuitemandroid-navigation

How to add the menu items using android navigation component


I'm trying to add a menu to the the toolbar of the application

My app is based on single-activity multi-fragment

and I'm using the navigation component my app style is:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

and I'm configuring the grapp in the MainActivity's onCreate method like that:

appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController,appBarConfiguration)

My question is how to add different custom menu items for the different fragments? also, I have added the back button how to handle it's clicks and hide it on the first fragment?


Solution

  • You seems to have it setup correctly. Please make sure your fragments have setHasOptionsMenu(true) (can be under onViewCreated) and that you are actually inflating menus under onCreateOptionsMenu of your fragments. Important to note your fragments title will be managed based on nav location (what is specified under android:label)