1

I'm trying to implement a bottomBarNavigation as I'm practicing how to use it. I'm confused , my menu is not showing as I'm trying to initialize it to a fragment. Please how do I do it?. Im still figuring how to use viewBinding.

these are my code :

Menu

<item
   android:id="@+id/nv_home"
    android:title="Home"
    android:icon="@drawable/ic_add_contact_background"/> 


<item
    android:id="@+id/nv_notification"
    android:title="Notification"
    android:icon="@drawable/ic_add_contact_background"/>

<item
    android:id="@+id/nv_profile"
    android:title="Profile"
    android:icon="@drawable/ic_add_contact_background"/>

Activity

private lateinit var binding: ActivityMain2Binding

override fun onCreate(savedInstanceState: Bundle?) {
    binding = ActivityMain2Binding.inflate(layoutInflater)
    super.onCreate(savedInstanceState)
    setContentView(binding.root)
    supportActionBar?.hide()

    val oneFragment = OneFragment()
    val twoFragment = TwoFragment()
    val threeFragment = ThreeFragment()

    setCurrentFragment(oneFragment)

    binding.bottomNavigationView.setOnItemSelectedListener {
        when(it.itemId){
            binding.nv_home-> setCurrentFragment(firstFragment)  // this is what I intended doing but the nv_home is not showing.
        }
    }
}

private fun setCurrentFragment(fragment : Fragment) = supportFragmentManager.beginTransaction().apply {
    replace(binding.frame_fragment,fragment)
    commit()
}
lpizzinidev
  • 12,741
  • 2
  • 10
  • 29
BlakOuz
  • 101
  • 1
  • 8

1 Answers1

1

As per the official documentation link:

View binding is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a binding class for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.

The view binding is available for the layout files as its using the findviewbyId(R.id.viewid) and in the case of menu items we use the menu.findItem(R.id.menuid) so the menu id's won't available in the binding variables

for the bottomnaviagtion use the menu id like this:

 binding.bottomNavigationView.setOnNavigationItemSelectedListener {
        when (it.itemId) {
            R.id.nv_home-> {
                 setCurrentFragment(firstFragment)
             }
              }
Rohini
  • 21
  • 5