Search code examples
android-studiokotlinandroid-navigationandroid-bottomnav

BottomNavigationView's menu not selected after navigating to other fragment, switching to other menu, and switching back to initial menu


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


Solution

  • After some days, I finally get the answer by myself. First, I need to get the BottomNavigationView from MainActivity, after that, you can just change the menu item value from another fragment.

    In MainActivity.kt:

    companion object {
        lateinit var binding: ActivityMainBinding
    {
    

    On Fragment,
    Define BottomNavigationView and set the desired index in onResume():

    class FAQFragment : Fragment() {
        private val navView: BottomNavigationView = MainActivity.binding.navView
    
        ...
    
        override fun onResume() {
            super.onResume()
    
            navView.menu.getItem(2).isChecked = true
        }
    }