【问题标题】:DataBinding not updating when passing LiveData<?> instead of ViewModel传递 LiveData<?> 而不是 ViewModel 时,DataBinding 未更新
【发布时间】:2021-11-04 07:56:51
【问题描述】:

我正在使用DataBinding,在我的ViewModel 中有一个LiveData&lt;MyItem&gt; 对象,我想将它绑定到我的布局。该项目有一个这样的属性:

@Bindable
public int getAmount() {
    return amount;
}

public void setAmount(int amount) {
    this.amount = amount;
    notifyPropertyChanged(BR.aMOUNT);
}

问题是,如果我在Fragment 中指出:

mDataBinding.setItem(mViewModel)

在我的布局中:

<Button
...
android:enabled="@{viewModel.item.amount == 0}/>

它绑定它,一旦 Item 中的属性 amountt 更改,启用或禁用按钮。好的。

问题变成了,我没有传递 viewModel 实例,而是直接传递了Item 实例:

mDataBinding.setItem(mViewModel.getItem().getValue())

在布局中:

<Button
...
android:enabled="@{item.amount == 0}/>

那么问题是它第一次正确地启用/禁用按钮,但是当项目的数量属性发生变化时它并没有改变它的状态。你知道为什么会发生吗??

【问题讨论】:

    标签: android mvvm android-livedata android-databinding android-viewmodel


    【解决方案1】:

    你能在viewModel之前设置binding.lifecycleOwner = this吗?此外,如果您使用片段,请使用 lifeCycleOwner 而不是 this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-14
      • 2020-05-17
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多