Android双向数据绑定(bind),textview不更新

标签 android android-databinding

我正在尝试将 MVVM 模式与 android 数据绑定(bind)一起使用。 我有一个 edittext 和一个 textview,当我通过使用 LocationType 模型对象通过 observablefield 绑定(bind)到模型来在 edittext 字段中键入内容时,它们应该显示相同的文本。

根据测试,当我启动应用程序时,这两个字段都设置为“hello”,正如预期的那样。 但是,当我在 edittextfield 中输入时, TextView 不会更新,即使模型对象正确更新,如通过调试可以看到的那样。

当我使用:

observablefield<String>

放弃使用模型,只需设置一些文本并更新 xml 以使用此字段。它按预期工作。

型号:

public class LocationType {
private String locationType;

public String getLocationType() {
   return locationType;
}

public void setLocationType(String locationType) {
  this.locationType = locationType;

 }
}

模型 View :

public class LocationTypeViewModel extends BaseObservable {
  @Bindable
  private    ObservableField<LocationType> locationTypeObservableField = new ObservableField<>();
  private Context context;
  LocationType locationType;

  public LocationTypeViewModel(Context context) {
    this.context = context;

    locationType = new LocationType();
    locationType.setLocationType("Hello");
    locationTypeObservableField.set(locationType);


  }

  public ObservableField<LocationType> getLocationTypeObservableField() {
    Log.d("CALLED GET", locationType.getLocationType());
    return locationTypeObservableField;
  }


}    

XML:

<layout xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <import type="android.view.View"/>

    <variable
        name="viewModel"
        type="fragment.LocationType.viewmodel.LocationTypeViewModel"/>
</data>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="@{viewModel.locationTypeObservableField.locationType}"
        android:id="@+id/edittext1"/>

    <TextView
        android:layout_below="@+id/edittext1"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="@{viewModel.locationTypeObservableField.locationType}"
        android:id="@+id/text"
        />




</RelativeLayout>
</layout>

最佳答案

android:text="@={viewModel.locationTypeObservableField.locationType}"

您忘记添加“=”。检查并将上面的行与您的代码进行比较。

关于Android双向数据绑定(bind),textview不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45640618/

相关文章:

android - 如何刷新我的gridView?

java - 将 Java 代码用于 Android 应用程序(用于 AES 加密)

android - ArrayAdapter的Textview占据整个屏幕

android-recyclerview - 双向数据绑定(bind)、RecyclerView、ViewModel、Room、LiveData、Oh My

java - 当也有 recyclerview 时,数据绑定(bind)无法在按钮上正常工作

android - 双向绑定(bind)无法解析 setter

Android:旋转更改后对话框等恢复

android - 使用代理推送通知

android - 如何通过 DI (Koin) 向 @BindingAdapter 方法提供某些内容?

java - 使用 Android DataBinding 时强制点 (“.” ) 作为小数点分隔符