如何将 Android DataBinding 绑定到 Menu? [英] How bind Android DataBinding to Menu?

查看:29
本文介绍了如何将 Android DataBinding 绑定到 Menu?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为它支持android中的数据绑定菜单?我写了这段代码,但错误:错误:(16, 26)没有指定资源类型(在‘可见’,值为‘@{item.visible}’)."

As it supports Data Binding menu in android? I write this code, but error: "Error:(16, 26) No resource type specified (at 'visible' with value '@{item.visible}')."

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
   <variable
        name="item"
        type="ru.dixy.ubiworkerchecklistsmobile.Models.Fact"/>
    <import type="android.view.View"/>
</data>
    <item
        android:id="@+id/compliteitem"
        android:title="mybutton"
        android:icon="@drawable/complite"
        android:visible="@{item.visible}"
        app:showAsAction="ifRoom"
         />
</menu>

推荐答案

目前数据绑定只针对布局资源,不针对菜单资源"

但是,该行为可以通过 Observable.OnPropertyChangedCallback 实现.首先你需要定义 OnPropertyChangedCallback:

But, the behaviour can be achieved with Observable.OnPropertyChangedCallback. First you need to define OnPropertyChangedCallback:

private final Observable.OnPropertyChangedCallback propertyChangedCallback = new Observable.OnPropertyChangedCallback() {
    @Override
    public void onPropertyChanged(Observable observable, int i) {
        getActivity().invalidateOptionsMenu();
    }
};

假设您的片段中有 Fact 模型的绑定:

Assuming that you have a binding for Fact model in your fragment:

<variable
    name="item"
    type="ru.dixy.ubiworkerchecklistsmobile.Models.Fact"/>

现在您需要注册 propertyChangedCallback 并在完成后取消注册:

Now you need to register propertyChangedCallback and unregister it when you are done with it:

@Override
public void onStart() {
    super.onStart();
    binding.getItem().addOnPropertyChangedCallback(propertyChangedCallback);
}

@Override
public void onStop() {
    super.onStop();
    binding.getItem().removeOnPropertyChangedCallback(propertyChangedCallback);
}

现在我们准备好根据Fact模型更新您的视图状态:

Now we are ready update your view state based on the Fact model:

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_fact, menu);
}

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    menu.findItem(R.id.compliteitem).setVisible(binding.getItem().isVisible());
}

这篇关于如何将 Android DataBinding 绑定到 Menu?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆