Reputation: 4037
I have a bottomnavigationview which is linked with navigation component using setupWithNavController(). It works as you would expect, pressing on the menu item will move me to a required window.
The problem is, that before redirecting to a different screen, I need to check if user is logged in or not and depending on that, I would need to redirect to a different screen.
So far it seems that I can use setOnNavigationItemSelectedListener() on my bottomnavigationview, but then I loose all the convenience of setupWithNavController() as then I have to manually specify all the destinations I want to go.
Are there any better ways to implement this?
Edit: My login screen is actually transparent so, going to required fragment and then showing login screen on top might be tricky
Upvotes: 3
Views: 918
Reputation: 11
bottomNav.setOnNavigationItemSelectedListener {
if (//not login) {
//to login fragment
false
} else {
NavigationUI.onNavDestinationSelected(it, homeController)
}
}
Upvotes: 1
Reputation: 1888
The problem is, that before redirecting to a different screen, I need to check if a user is logged in or not and depending on that, I would need to redirect to a different screen.
In this case, you can use OnDestinationChangedListener
like this:
navController.addOnDestinationChangedListener { controller, destination, arguments ->
if(destination.id == R.id.nav_profile && !isLoggedIn()){
//Immediately pop the fragment
controller.popBackStack()
//Navigate to the login fragment
controller.navigate(R.id.nav_login)
}
}
Here, the required fragment is removed from the back stack. And by this, you should not worry about transparent background of your login screen. Also, you won't lose any of the convenience of setupWithNavController()
However, you should make sure that the method isLoggedIn()
is fast enough. Otherwise, a user might see the require function before it gets removed from the back stack.
Upvotes: 0