我想用Android数据绑定使用MVVM模式。 我有一个edittext和一个textview,当我通过带有LocationType模型对象的observablefield绑定到模型来输入edittext字段时应该显示相同的文本。Android双向数据绑定,textview不更新
从测试这两个字段都设置为“你好”,当我启动应用程序,如预期的那样。 但是,当我输入edittextfield的时候,textview并没有更新,甚至很难通过调试来看到模型对象被正确更新。
当我使用:使用模型,只是设置一些文本和更新使用该领域的XML
observablefield<String>
下降。它按预期工作。
型号:
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>
谢谢!我有@ =之前不知道它是如何迷路的。但是,我怎样才能将模型作为POJO? – Morti
您可以让LocationType对象扩展BaseObservable,然后当某个字段发生变化时应该遵守,您需要从BR生成的类中通知正确的ID。查看文档中的Observable对象:https://developer.android.com/topic/libraries/data-binding/index.html。那里有一个相对的例子。 –
我明白了,是为MVVM模式设计时做的事吗?在大多数例子中,Viewmodel是扩展BaseObservable的一个例子。 – Morti