Search code examples
androidandroid-databindingandroid-menuandroid-viewbinding

View binding for menu files?


Is it possible to use View Binding (or Data Binding) in menu resources?

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    menuInflater.inflate(R.menu.menu_main, menu)
    
    // search using ID - can this be replaced by view binding?
    val searchView = menu.findItem(R.id.menu_search).actionView as SearchView
}

Solution

  • In most cases, view binding replaces findViewById.

    According to the documentations:

    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.

    Where in menus it uses findItem() and not findViewById() method.