I’m building an android application with 3 menus using bottom navigation. I created new project in Android Studio using Bottom Navigation Activity.
I renamed the fragment to:
-
InfoFragment.kt
-
DetectFragment.kt
-
AboutFragment.kt
Renamed the layout in src/main/res/layout
to:
-
fragment_info.xml
-
fragment_detect.xml
-
fragment_about.xml
Renamed the menu in src/main/res/menu
to:
-
navigation_info
-
navigation_detect
-
navigation_about
In the fragment_about.xml
I added a Button buttonGoToFAQ
to navigate to fragment_faq
like this with this code in AboutFragment.kt
buttonGoToFAQ.setOnClickListener {
val action = AboutFragmentDirections.actionFAQ()
Navigation.findNavController(it).navigate(action)
}
After I clicked BottomNavigationView menu either navigation_info
or navigation_detect
, and go back by clicking navigation_about
menu, the selected menu on the BottomNavigationView is not changed.
See this picture.
What I want is the menu navigation_about
should have been selected instead of other menu.
I already tried overriding fun onStart()
and fun onResume()
in FAQFragment.kt
but to no avail.
nav_view
is my BottomNavigationView.
override fun onStart() {
super.onStart()
(requireActivity().findViewById<View>(R.id.nav_view) as BottomNavigationView).selectedItemId =
R.id.navigation_about
}
I also recognize that all the BottomNavigationView menu’s id have the same ids as the id in the src/main/res/navigation
xml file
4
Answers
After some days, I finally get the answer by myself. First, I need to get the
BottomNavigationView
fromMainActivity
, after that, you can just change the menu item value from another fragment.In
MainActivity.kt
:On Fragment,
Define
BottomNavigationView
and set the desired index inonResume()
:You can navigate manually and always return
true
to theOnItemSelectedListener
to achieve menu item selection.This is the intended behavior, according to this link to Google’s Issue tracker – https://issuetracker.google.com/issues/210687967?pli=1
In a nutshell, Google wants us to use Nested Navigation Graphs to link
FaqFragment
andAboutFragment
.This will result in menu
navigation_about
to be selected whenever either of the fragments are opened.nav_graph.xml
, add a nested graph –bottom_nav_menu.xml
As also suggested by @Francis, this is what you’re looking for. I saw your answer but that is not the optimal solution, that is just a workaround that you have found.