Search code examples
androidandroid-layoutbottomnavigationviewandroid-bottomnav

BottomNavigationView switching between activities - solutions appear deprecated?


I am using a BottomNavigationBar and as per recent blogs and research, it seems the best way to flick between activities using this bar is to use the setInNavigationItemSelectedListener.

The issue is - this is deprecated.

setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView.OnNavigationItemSelectedListener)' is deprecated

Recent articles suggest this is the way to allow changing between activities via a BottomNavigationBar and therefore I am not sure of alternative.

The deprecation doesn't appear to offer a good alternative that is safe to use. Can somebody suggest what would be non deprecated approach?


Solution

  • You need to use setOnItemSelectedListener()

    Like this

    bottomBar.setOnItemSelectedListener { menuItem ->
      when (menuItem.itemId) {
        R.id.home -> {
          return@setOnItemSelectedListener true
        }
    
        R.id.profile -> {
          return@setOnItemSelectedListener true
        }
    
        R.id.cart -> {
          return@setOnItemSelectedListener true
        }
    
      }
      false
    }