user2638180
user2638180

Reputation: 1023

Checking a MenuItem in a BottomNavigatorBar in Kotlin

I want in my app a button that when pressed sucessfully navigates as if the user had pressed the second available button that is the BottomNavigatorBar.

I've mostly achieved the desired behavior by defining an static function which when called from another fragment if mostly imitates the sam behavior that would happen if the user had pressed that button:

That's its code:

  companion object
    {
        […]
        fun calledFun(it: MenuItem, binding: FragmentContainerBinding) {
            when (it.itemId) {

            R.id.nav_assets -> binding.vpPrivate.currentItem = 0
            R.id.nav_incidents -> binding.vpPrivate.currentItem = 1
            R.id.nav_profile -> binding.vpPrivate.currentItem = 2



        }

        it.isChecked=true

    }
}

But unluckily the it.isChecked, that I think should put the corresponding MenuItem to red color, doesn't work, it keeps showing on the same MenuItem that was selected when the button I first mention has been pressed.

It has been checked, that despite that, it's really showing what should show with that MenuItem. Indeed, if I press the MenuItem with red color, content changes to the one it were.

How can I mark that MenuItem as if the user had selected it?

Upvotes: 1

Views: 214

Answers (1)

DemoDemo
DemoDemo

Reputation: 392

If you wish to achieve just selecting an item in the navbar you can do something like this

testing.setOnClickListener {
        navView.setOnNavigationItemSelectedListener(null)
        navView.menu.getItem(0).isChecked = true
        navView.setOnNavigationItemSelectedListener(this)
    }

It's similar in a way when you are working with checkbox's/radiobuttons but you don't want to trigger the functionality when you change the selected state.

Upvotes: 1

Related Questions