I have created a nav_graph.xml for android navigation component and added four fragments for four different views. Now added BottomNavigationView and menu items , used the fragment ids from nav_graph and provided those ids to each menu items for bottom navigation. It works and shows the particular fragment for selected menu item from bottom nav view.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/nav_fragmentA"
android:title="@string/menu_search"
android:icon="@drawable/ic_search" />
<item android:id="@+id/nav_fragmentB"
android:title="@string/menu_settings"
android:icon="@drawable/ic_add" />
<item android:id="@+id/nav_fragmentC"
android:title="@string/menu_navigation"
android:icon="@drawable/ic_action_navigation_menu" />
<item android:id="@+id/nav_fragmentD"
android:title="@string/menu_navigation"
android:icon="@drawable/ic_action_navigation_menu" />
</menu>
Issue: When user presses any menu items multiple times and presses back button. It navigates through whole back stack rather going to first menu item and exiting the app.
For example
Want to achieve the behaviour as below:
I had this same issue.
The integration between the bottom navigation and the navigation component needs a separate nav graph for each fragment/tab and also a parent nav graph that includes all of these tabs.
The parent nav graph cannot have any other fragments included within it. It can only have the include tags for each of the tabs.
Example:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:startDestination="@id/home"
android:id="@+id/bottom_nav">
<include app:graph="@navigation/frag1" />
<include app:graph="@navigation/frag2" />
<include app:graph="@navigation/frag3" />
</navigation>
The sample given by architecture components is also helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With