Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Databinding for Options menu in Android Studio?

The following code is from the project architecture-samples, you can see it here.

I know that I can use such as viewDataBinding.viewmodel to access layout control or data.

But in the following code, I find val view = activity?.findViewById<View>(R.id.menu_filter) ?: return is appear, it's a traditional code.

Is there a way to access Options menu with Databinding or Viewbinding technology ?

class TasksFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewDataBinding = TasksFragBinding.inflate(inflater, container, false).apply {
            viewmodel = viewModel
        }
        setHasOptionsMenu(true)
        return viewDataBinding.root
    }

    override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            R.id.menu_clear -> {
                viewModel.clearCompletedTasks()
                true
            }
            R.id.menu_filter -> {
                showFilteringPopUpMenu()
                true
            }
            R.id.menu_refresh -> {
                viewModel.loadTasks(true)
                true
            }
            else -> false
        }


  private fun showFilteringPopUpMenu() {
        val view = activity?.findViewById<View>(R.id.menu_filter) ?: return

        PopupMenu(requireContext(), view).run {
            menuInflater.inflate(R.menu.filter_tasks, menu)

            setOnMenuItemClickListener {
                viewModel.setFiltering(
                    when (it.itemId) {
                        R.id.active -> TasksFilterType.ACTIVE_TASKS
                        R.id.completed -> TasksFilterType.COMPLETED_TASKS
                        else -> TasksFilterType.ALL_TASKS
                    }
                )
                true
            }
            show()
        }
    }

    ...
}


<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <import type="android.view.View" />

        <import type="androidx.core.content.ContextCompat" />

        <variable
            name="viewmodel"
            type="com.example.android.architecture.blueprints.todoapp.tasks.TasksViewModel" />

    </data>
    ...
</layout>
like image 369
HelloCW Avatar asked Apr 29 '20 08:04

HelloCW


People also ask

What is the use of databinding in Android?

Data Binding Library Part of Android Jetpack. The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.

Which method is used to create the Options menu in Android Studio?

In android, to define options menu, we need to create a new folder menu inside of our project resource directory (res/menu/) and add a new XML (options_menu. xml) file to build the menu. Now open newly created xml (options_menu.

Is Android databinding deprecated?

Recently Android has announced that with Kotlin 1.4. 20, their Android Kotlin Extensions Gradle plugin will be deprecated and will no longer be shipped in the future Kotlin releases. Android Kotlin Extensions plugin brought with it two very cool features : Synthetics let you replace calls to findViewById with kotlinx.

Can we use databinding in MVP?

Why use Data binding with Mvp? Combining Databinding along wih MVP pattern can result in a very clean structure and maintainable project. Databinding saves u a lot of stress and uneccesary long lines of code. Your UI is updated eaily and gone are those days where you need "findViewById" and onclick listeners and so on.


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.

like image 143
Anggrayudi H Avatar answered Oct 09 '22 13:10

Anggrayudi H