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

时间:2017-08-11 17:19:47

标签: android android-databinding

我正在尝试使用带有android数据绑定的MVVM模式。 我有一个edittext和textview,当我通过带有LocationType模型对象的observablefield绑定到模型时输入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;

 }
}

MODELVIEW

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>

1 个答案:

答案 0 :(得分:1)

双向数据绑定应该是这样的   android:text =“ @ = {ProfileViewModel.mobileNumber}” 您忘记添加“ =”

相关问题