Disable item selection in bottom nav bar

124 Views Asked by At

Okay so my case is that for certain scenarios, one or multiple items in the bottom nav bar would have the following behaviour:

  1. The click for the item will show a popup
  2. the popup can be cancelled
  3. the clicked item will not navigate the user anywhere
  4. the clicked item will not navigate the user anywhere
  5. the clicked item should NOT be selected

All of my use cases are being done but even though no navigation is performed, the clicked item becomes selected. I need the bottom bar to stay on the state if no navigation was done.

binding.bottomNavigation.setOnItemSelectedListener {

        
        when (it.itemId) { 
           R.id.referral_bottom_nav -> {
            //handles when to navigate and when to show popup
                true        
              }
    }
}

How do I do this?

1

There are 1 best solutions below

0
MeLean On

In Android, the BottomNavigationView's selected item is automatically updated when an item is clicked. This is the default behavior and it's not straightforward to change it. However, you can use a workaround to achieve your desired behavior.

var previousMenuItem: MenuItem? = null

binding.bottomNavigation.setOnNavigationItemSelectedListener { menuItem ->
    when (menuItem.itemId) {
        R.id.referral_bottom_nav -> {
            // Show your popup here

            // If the previousMenuItem is not null, reselect it
            previousMenuItem?.let { binding.bottomNavigation.selectedItemId = it.itemId }

            false // Return false to not update the selection
        }
        else -> {
            // Update the previousMenuItem
            previousMenuItem = menuItem

            // Navigate to the selected screen

            true // Return true to update the selection
        }
    }
}

In this code, we're storing the previously selected menu item in previousMenuItem. When an item is clicked, we check its id. If it's the id of the item that should show a popup and not update the selection, we reselect the previously selected item (if it's not null) and return false to not update the selection. If it's another item, we update previousMenuItem and navigate to the selected screen, then return true to update the selection.

Please replace R.id.referral_bottom_nav with the actual id of the menu item that should show the popup and not update the selection.