I'm using BottomNavigationView with Navigation component. When I click the back button, the Fragment stack is correctly handled, but the BottomNavigationView doesn't change and stays blocked on the last state.
I made sure to have the same ids in my nav_graph and the BottomNavigationView's items.
My nav_graph.xml
:
<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/nav_graph"
app:startDestination="@id/journalFragment">
<fragment
android:id="@+id/journalFragment"
android:name="com.example.Fragment1"
android:label="@string/navigation_title_journal"
tools:layout="@layout/fragment_journal"/>
<fragment
android:id="@+id/toolsFragment"
android:name="com.example.Fragment2"
android:label="@string/navigation_title_tools"
tools:layout="@layout/fragment_tools" />
</navigation>
My bottom_navigation_menu
:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/journalFragment"
android:enabled="true"
android:title="@string/navigation_title_journal" />
<item
android:id="@+id/toolsFragment"
android:enabled="true"
android:title="@string/navigation_title_tools" />
</menu>
In MainActivity's onCreate()
:
NavHostFragment navHostFragment =
(NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_container);
navController = navHostFragment.getNavController();
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.journalFragment, R.id.toolsFragment).build();
setupWithNavController(mToolbar, navController, appBarConfiguration);
bottomNavigationView.setOnItemSelectedListener(item -> {
Log.d("MainActivity", "setOnItemSelectedListener-------");
switch (item.getItemId()) {
case R.id.dreamJournalFragment -> navController.navigate(R.id.dreamJournalFragment);
case R.id.statisticsFragment -> navController.navigate(R.id.statisticsFragment);
case R.id.toolsFragment -> navController.navigate(R.id.toolsFragment);
case R.id.wikiFragment -> navController.navigate(R.id.wikiFragment);
}
return true;
});
bottomNavigationView.setOnItemReselectedListener(item -> {
// Ignore
});
In activity_main
:
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_navigation_menu" />
You haven't connected the navigation controller to the bottom navigation view. To resolve this, you can include the following code:
bottomNavigationView.setupWithNavController(navController)