Home > Back-end >  Implementing multiple navigation actions on a single menuitem button in Kotlin(android)
Implementing multiple navigation actions on a single menuitem button in Kotlin(android)

Time:08-10

I am trying to implement a way for the menuitem button to navigate to a different fragment based on the current fragment.

For example, if I am in the fragment_home, I can access the dog_fragment and from the dog_fragment I can access another fragment like cat_fragmentand vice versa.

So far I am only able to navigate from fragment_home to dog_fragment, however when I try to access any other fragments from the dog_fragment my app crash. If I try to access another fragment from any other fragment accept from the home_fragment my app crashes

//This is in the Mainactivity
fun onComposeAction(item: MenuItem) {
    val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
    val navController = navHostFragment.navController
    when (item.getItemId()) {
        R.id.Hamster -> {
            navController.navigate(R.id.action_home2_to_hamster)
            
        }
        R.id.Dog -> {
            navController.navigate(R.id.action_home2_to_dog)

        }
        R.id.Cat ->{
            navController.navigate(R.id.action_home2_to_cat)
        }
    }
}

CodePudding user response:

Simply tie the menuitems to the destination fragments you have.

  • Related