问题
I am using BottomNavigationView with nav-graph
Below is my code
InMainActivity.class
navController = Navigation.findNavController(this, R.id.mainFragment);
bottomNavigation.setOnNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId()){
case R.id.home:
navController.navigate(R.id.exploreFragment);
return true;
case R.id.events:
navController.navigate(R.id.eventsFragment);
return true;
case R.id.stories:
navController.navigate(R.id.storiesFragment);
return true;
}
return false;
});
activity_main.xml
<fragment
android:id="@+id/mainFragment"
app:defaultNavHost="true"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/nav_home"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
app:itemIconTint="@drawable/bottom_navigation_color"
app:itemTextColor="@drawable/bottom_navigation_color"
android:background="@color/grey_50"
android:id="@+id/bottomNavigation"
app:menu="@menu/bottom_navigation"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_height="wrap_content"/>
<include
layout="@layout/toolbar"
android:id="@+id/toolbar"/>
nav_home.xml
<fragment
android:id="@+id/exploreFragment"
android:name="com.decathlon.allforsport.home.explore.ExploreFragment"
tools:layout="@layout/fragment_explore" />
<fragment
android:id="@+id/eventsFragment"
android:name="com.decathlon.allforsport.home.events.EventsFragment"
tools:layout="@layout/fragment_stories" />
<fragment
android:id="@+id/storiesFragment"
android:name="com.decathlon.allforsport.home.stories.StoriesFragment"
tools:layout="@layout/fragment_stories" />
So problem is when I tap on Home in BottomNavigationView, it reloads the fragment again and again. I tried many ways, but no success.
回答1:
Since you are using navigation controller, you can remove setOnNavigationItemSelectedListener function.
In bottom_navigation menu, make sure you define the item id same as the id you defined in nav graph.
And you need those code to make the bottom navigation bar works
setupActionBarWithNavController(navController!!)
bottomNavigation.setupWithNavController(navController!!)
Edit
For androidx
NavigationUI.setupWithNavController(bottomNavigation,
Navigation.findNavController(this, R.id.mainFragment))
来源:https://stackoverflow.com/questions/55178578/bottomnavigationview-with-navgraph-loading-fragment-again