Home » Android » BottomNavigationView on databinding inside viewmodel

BottomNavigationView on databinding inside viewmodel

Posted by: admin November 1, 2017 Leave a comment

Questions:

layout:

<android.support.design.widget.BottomNavigationView
                android:id="@+id/navigation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
             app:onNavigationItemSelected="@{viewModel.onNavigationItemSelected}"
                android:background="?android:attr/windowBackground"
                app:menu="@menu/menu_home_tab" />

code:

@BindingAdapter("onNavigationItemSelected")
    public static void setOnNavigationItemSelected(
            BottomNavigationView view, BottomNavigationView listener) {
        view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.navigation_dashboard:
                        Log.d("test","test1");
                        return true;
                    case R.id.navigation_notifications:
                        Log.d("test","test2");
                        return true;

                }
                return false;
            }

        });

    }

This returns an error

Error:(183, 49) Could not find accessor viewmodel.onNavigationItemSelected 

I am trying to implement databinding on my bottomnavigationview

Answers:

You should have onNavigationItemSelected() declared in your viewModel class:

class ViewModel {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_dashboard:
                Log.d("test","test1");
                return true;
            case R.id.navigation_notifications:
                Log.d("test","test2");
                return true;
        }
        return false;
    }
}

In your xml, use method reference:

app:onNavigationItemSelected="@{viewModel::onNavigationItemSelected}"