How to use viewbinding in menu items

Viewed 518

The problem that I faced is I cannot retrieve the binding id of my menu items.
HomeFragment ->includes(HomeActivity) ->includes(BottomNavigation)

 //bottom navigation
    fun getBottomNavigation(){
           val bottomNavigation = binding!!.includeBottomNavigation.bottomNavigation
           bottomNavigation.itemIconTintList = null
            bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelected)
       }
 private val mOnNavigationItemSelected = BottomNavigationView.OnNavigationItemSelectedListener{ menuItem ->
        when (menuItem.itemId) {
            R.id.navigation_home -> {  

//the issue what is, I want to use binding. navigation_home but it doesnot occur

 return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_chapter -> {
                    return@OnNavigationItemSelectedListener true
                }
                R.id.navigation_store -> {
                    return@OnNavigationItemSelectedListener true
                }
            }
            false
        }

//menu items   
 <menu
    xmlns:android="http://schemas.android.com/apk/res/android"
            <item
            android:id="@+id/navigation_home"
            android:enabled="true"
            android:icon="@drawable/ic_home"
            android:title="" />
        
        <item
            android:id="@+id/navigation_notification"
            android:enabled="true"
            android:icon="@drawable/ic_notification"
            android:title="" />
    </menu>
1 Answers

As states in the docs:

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.

In most cases, view binding replaces findViewById.

Look at the bold words, you notice that View Binding only works for XML layout (located in res/layout), whereas the menus are located in res/menu.

Also, View Binding uses findViewById, whereas menus use menu.findItem(R.id.menu_id), thus it is not possible.

In persent time,ViewBinding and DataBinding is only for layout resources xml files, not menu resources and others.

Related