Search code examples
androidbottomnavigationviewandroid-navigation

How to change bottom navigation menu item to another fragment programmatically android kotlin?


I am using BottomNavigationView and Navigation Component.

Let's say I have 3 items in my menu, each of which leads to some fragment.

However, I needed to change some menu item to another fragment. How can i do this programmatically?

Menu XML code:

<item
    android:id="@+id/homeFragment"
    android:icon="@drawable/vector_home"
    android:title="Home" />
<item
    android:id="@+id/newsFragment"
    android:icon="@drawable/vector_news"
    android:title="News" />
<item
    android:id="@+id/settingsFragment"
    android:icon="@drawable/vector_settings"
    android:title="Settings" />

Setup menu in Activity code:

binding.apply {
    val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment

    val bottomNavViewLP = navView.layoutParams as CoordinatorLayout.LayoutParams
    bottomNavViewLP.behavior = BottomNavigationViewHideBehavior(this)

    val navController = navHostFragment.navController

    navView.setupWithNavController(navController)
}

Solution

  • Add below code to override bottomNavView's item clicks, so you can direct them to another fragment:

            navView.setOnItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.homeFragment -> {
                        NavigationUI.onNavDestinationSelected(item, navController)
                        navController.popBackStack(item.itemId, inclusive = false)
                    }
                    R.id.newsFragment -> {
                        // Now news fragment item also navigates to settings
                        // And we remove it from backstack completely
                        navController.navigate(R.id.settingsFragment)
                        navController.popBackStack(item.itemId, inclusive = true)
                    }
                    R.id.settingsFragment -> {
                        NavigationUI.onNavDestinationSelected(item, navController)
                        navController.popBackStack(item.itemId, inclusive = false)
                    }
                }
                true
            }