Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottom navigation setOnItemSelectedListener return super

Tags:

android

kotlin

I have botton navation setup up as below and it works all right.

navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(setOf(R.id.nav_1, R.id.nav_2))
setupActionBarWithNavController(navController, appBarConfiguration)
binding.bottomNavView.setupWithNavController(navController)

Now I would like to prevent switching fragments if current fragment is the second one and it has some flag set in it.

I've tried using bottomNavView.setOnItemSelectedListener but it breaks the entire nav controller mechanism and requires doing fragment and title swithcing by yourself.

Is there any other way of overriding nav controller behaviour for a pariticular item and let it handle the rest as usual with something like super.onItemSelected()?

like image 441
yaugenka Avatar asked Sep 14 '25 19:09

yaugenka


1 Answers

As per the setupWithNavController() documentation:

This will call onNavDestinationSelected when a menu item is selected.

So you can simply call that method if you want to do the default behavior from your own listener.

// Call setupWithNavController to get the automatic
// selection of the correct bottom nav item
// based on the NavController's state
binding.bottomNavView.setupWithNavController(navController)
// Then override the OnItemSelectedListener
// with your own with your custom logic
binding.bottomNavView.setOnItemSelectedListener { item ->
    if (navController.currentDestination?.id == R.id.fragment_id && !yourConditionIsMet) {
        // Return false to not allow navigating to the tab
        false
    } else {
        // Do the default behavior
        onNavDestinationSelected(
            item,
            navController
        )
    }
}
like image 51
ianhanniballake Avatar answered Sep 17 '25 09:09

ianhanniballake