Home > Blockchain >  How to see when Fragment Change to another fragment in Navigation Component
How to see when Fragment Change to another fragment in Navigation Component

Time:10-20

Problem

I have a BottomNavigationView in which I used Navigation Component to display fragments. I need to check a condition every time the user clicks on an item in the BottomNavigationView. What would be the most correct way to do this using navigation components?

What I did: (Is there a more efficient way to do this?)


 val navController = findNavController(R.id.fragment)//this line I dont use it
 binding.bottomNav.setupWithNavController(navController) //this line I dont use it

binding.bottomNav.apply {
            setOnNavigationItemReselectedListener {
                if (it.itemId == R.id.homeFragment) {
                    if(theUserWasLogged()){
                        setFragment(new HomeFragment())
                    }else{
                        displayDialogLogIn()
                    }

                } else if (it.itemId == R.id.avisosFragment) {
                    
                    setFragment(new avisosFragment())
                }else{
                    displayDialogLogIn()
                }
                }

            }

CodePudding user response:

To implement navigation using the navigation component inside your setOnNavigationItemReselectedListener, you should use navController and directly call your your destination id or action id defined in you navigation graph, in your case, replace the setFragment() with navController.navigate(), i.e.

setOnNavigationItemReselectedListener {
    if (it.itemId == R.id.homeFragment) {
        if(theUserWasLogged()){
            navController.navigate(R.id.homeFragment)
        }else{
            displayDialogLogIn()
        }
    } else if (it.itemId == R.id.avisosFragment) {
        navController.navigate(R.id.avisosFragment)
    }else{
        displayDialogLogIn()
    }
}

and also I think can use when instead if to have more concise code

setOnNavigationItemReselectedListener {
    when (it.itemId) {
        R.id.homeFragment -> {
            if(theUserWasLogged()) {
                navController.navigate(R.id.homeFragment)
            } else {
                displayDialogLogIn()
            }
        }
        R.id.avisosFragment -> navController.navigate(R.id.avisosFragment)
        else -> displayDialogLogIn()
    }
}
  • Related