布局:

<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" />

代码:
@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;
            }

        });

    }

这将返回一个错误
Error:(183, 49) Could not find accessor viewmodel.onNavigationItemSelected

我正在尝试在我的bottomnavigationview上实现数据绑定(bind)

最佳答案

您应该在onNavigationItemSelected()类中声明了viewModel:

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;
    }
}
在您的xml中,使用方法引用:
app:onNavigationItemSelected="@{viewModel::onNavigationItemSelected}"

关于android - BottomNavigationView在ViewModel内部进行数据绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46872747/

10-10 08:48
查看更多