0

I'm trying to set up conditional navigation for my Fragments using the Navigation components and a BottomNavigationView. Current setup (without conditions):

val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
NavigationUI.setupWithNavController(bottom_navigation, navController)

General navigation is working fine, but I want to restrict user interaction with the bottom navigation based on conditions. If the condition is not met at the time of clicknig the menu item, this should only result in showing a Toast instead of navigating to the next fragment.

I already looked up this but the solution mentioned there involves navigating to the next fragment first and then check the conditions - but I want to avoid this.

Thank you very much.

Sebastian
  • 90
  • 7

1 Answers1

0

Expose LiveData that will stream which @Ids are disabled.

class MainViewModel{

  val disableNavigation = MutableLiveData<@Ids Int>() 

   fun invalidateNavigation() {
     val canNavigate = ....
     if(!canNavigate){
        disableNavigation.value = R.id.bottom_nav_item_x
     }
   }

}

Then just observe this:

mainViewModel.observe(viewLifecycleOwner){
  //disable the id here
  //re-enable the rest of the items
}
Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
  • Hey Nikola, thanks for this input - I thought about this before but was not able to add an "Error Message" for the user when trying to tap on an disabled ID. Do you have any idea on how to solve this? I tried to place a NavigationItemSelectedListener for my bottom_navigation, but this gets overridden by "setupWithNavController" Thank you very much – Sebastian Nov 11 '20 at 14:46
  • You should disable the item in the bottom nav view. you can also display error message in the same block, because it will be called everything there is some menu item in the nav view disabled. – Nikola Despotoski Nov 11 '20 at 15:21