【问题标题】:Android : Databinding, notifyPropertyChanged() not working?Android:数据绑定,notifyPropertyChanged() 不起作用?
【发布时间】:2015-12-15 16:50:30
【问题描述】:

我正在使用 Android 的数据绑定库。我有我的数据对象扩展BaseObservable

public static class SimpleData extends BaseObservable implements Serializable {
    private String text, subText;
    private SpannableString totalText;

    @Bindable
    public SpannableString getTotalText() {
      return totalText;
    }

    public void setTotalText(SpannableString totalText) {
      this.totalText = totalText;
      notifyPropertyChanged(BR.totalText);
    }
}

我的xml也被绑定了

<TextView
    android:id="@+id/patient_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_marginLeft="16dp"
    android:layout_toRightOf="@+id/patient_image"
    android:textColor="@color/primary_text"
    android:text="@{object.getTotalText()}"/>

绑定发生在初始值上。但是当我使用

更改值时
object.setTotalText(someSpannableString);

更改不会反映在文本视图中。可能是什么问题?

【问题讨论】:

  • 您能解决您的问题吗?
  • @mahdipishguy:不,先生。问题还没有解决

标签: android android-databinding


【解决方案1】:

使用字段名称而不是 getter。

<TextView
    android:id="@+id/patient_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_marginLeft="16dp"
    android:layout_toRightOf="@+id/patient_image"
    android:textColor="@color/primary_text"
    android:text="@{object.totalText}"/>

【讨论】:

  • 似乎不正确,您应该使用BR 类来识别字段AND 将setter 和getter 都用@Bindable 注释
【解决方案2】:

双向数据绑定需要加=

android:text="@={LoginViewModel.address}"

我忘了添加=,所以它不起作用。如果您使用的是EditText,那么想要通过基础BaseObservable 进行两种数据绑定,那么您 需要@={LoginViewModel.address} 而不是@{LoginViewModel.address}

【讨论】:

  • 这对我有用谢谢:)
【解决方案3】:

我也遇到了同样的问题。我的绑定第一次可以工作,然后第二次就不行了。

我的设置与你的设置相同,只是我将 @Bindable 放在我的 setter 而不是我的 getter 方法上。

@Bindable 添加到我的 setter 和 getter 为我解决了这个问题。

当我调试数据绑定库的内部工作人员时,我 注意到没有调用名为 request re-bind 的方法 因为它执行了一个操作来检查该字段是否已更新 从最后一个值。我的猜测是你需要两者的注释 方法,以便它可以进行内部确认以检查它是否 是否需要重新绑定。

无论这是否属实,我都不是 100%,但是在这两种方法上都有注释解决了我的问题。查看 Data Binding 库文档,我注意到它们只是在 getter 上显示注释。

你可以试试:

@Bindable
public SpannableString getTotalText() {
  return totalText;
}

@Bindable
public void setTotalText(SpannableString totalText) {
  this.totalText = totalText;
  notifyPropertyChanged(BR.totalText);
}

看看能不能解决。

【讨论】:

    【解决方案4】:

    我认为您应该将String 值定义为public 而不是private。 数据绑定也会自动检测 getter 和 setter,因此只需键入 @{object.totalText} 即可。

    我希望这个 Youtube 链接也对你有帮助。

    https://www.youtube.com/watch?v=h6ejIx5xu-M

    【讨论】:

      【解决方案5】:

      使用notifyChange() 代替notifyPropertyChanged(BR._)

      【讨论】:

      • 请删除您的评论,notifyPropertyChanged 适用于数据绑定
      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 2019-11-08
      • 2021-02-22
      • 2016-06-23
      • 1970-01-01
      • 2016-12-11
      • 2016-04-19
      • 1970-01-01
      相关资源
      最近更新 更多