Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Back button behaviour with BottomNavigationView implemented using navigation component

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

  • Four bottom menu items: A B C D
  • User navigation: A->C->B->D->B->C-A->D
  • Back button behaviour: D->A->C->B->D-B->C->A->Exit (Reverse of user navigation)

Want to achieve the behaviour as below:

  • User navigate through menu items: A->C->B->D->B->C-A->D (Any random navigation)
  • Back button: D->A->Exit (From any selected item to first item and then exit)
like image 608
takharsh Avatar asked Jun 23 '26 14:06

takharsh


1 Answers

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.

like image 192
LionKing52 Avatar answered Jun 27 '26 03:06

LionKing52



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!