Android双向数据绑定,textview不更新 [英] Android two-way databinding, textview not updating
问题描述
我正在尝试将MVVM模式与android数据绑定一起使用. 我有一个edittext和一个textview,当我通过一个带有LocationType模型对象的observablefield绑定到模型时,在edittext字段中键入内容时应该显示相同的文本.
I am trying to use MVVM pattern with android databinding. I have an edittext and a textview that should show the same text when I type in the edittext field by binding to the model via the observablefield with a LocationType model object.
从测试开始,按预期,当我启动应用程序时,两个字段都设置为"hello". 但是,当我在edittextfield中键入内容时,textview不会更新,即使很难调试,模型对象也能正确更新.
From testing both fields are set to "hello" when I start the app, as expected. But when I type in the edittextfield the textview does not update, even tough the model object gets updated correctly as can be seen with by debug.
当我使用时:
observablefield<String>
使用模型拖放并设置为一些文本,然后更新xml以使用此字段.它按预期工作.
drop using the model and just set to some text and update the xml to use this field. It works as intended.
型号:
public class LocationType {
private String locationType;
public String getLocationType() {
return locationType;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
}
模型视图:
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:text="@={viewModel.locationTypeObservableField.locationType}"
您忘了添加"=".检查并将上面的代码与您的代码进行比较.
You forgot to add "=" .check and compare above line with your code.
这篇关于Android双向数据绑定,textview不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!