【发布时间】:2019-05-04 21:17:12
【问题描述】:
我在使用 LiveData 进行双向数据绑定时遇到问题。我有一个带有MutableLiveData<Ingredient> ingredient 的 ViewModel。在 XML 布局中,我想用 ingredient.title 属性初始化 EditText 视图。我试过这个:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="UpdateIngredientViewModel" />
</data>
<RelativeLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/updateIngredient_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:paddingStart="15dp"
android:paddingEnd="15dp"
android:text="@={viewModel.ingredient.getValue().title}"
android:layout_centerHorizontal="true"
android:layout_below="@+id/updateIngredient_label"
android:textAlignment="center"
android:hint="@string/Title"
android:inputType="text"/>
</RelativeLayout>
</layout>
所以使用这一行android:text="@={viewModel.ingredient.getValue().title}" 初始化成分的标题值,但是如果我更改EditText 中的文本并旋转显示,例如,我不会得到更改的值,而是初始化的值。有人可以帮我解决这个问题吗?
这是我的 ViewModel:
public class UpdateIngredientViewModel extends AndroidViewModel {
private MutableLiveData<Ingredient> ingredient;
public UpdateIngredientViewModel(@NonNull Application application) {
super(application);
}
public LiveData<Ingredient> getIngredient() {
if (ingredient == null) {
ingredient = new MutableLiveData<>();
}
return ingredient;
}
public void setIngredient(Ingredient ingredient) {
this.ingredient.setValue(ingredient);
}
}
编辑
这是成分类:
public class Ingredient {
@SerializedName("ingredient_ID")
private int ingredient_ID;
@SerializedName("title")
private String title;
public Ingredient(int ingredient_ID, String title) {
this.ingredient_ID = ingredient_ID;
this.title = title;
}
public int getIngredient_ID() {
return ingredient_ID;
}
public void setIngredient_ID(int ingredient_ID) {
this.ingredient_ID = ingredient_ID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
我也尝试像android:text="@={viewModel.ingredient.title}" 一样更改EditText 属性,但它似乎与原始帖子中的工作方式相同。
【问题讨论】:
-
Ingredient长什么样子? -
@CommonsWare 我在编辑问题时提供了
Ingredient -
如果在
setTitle()中下断点,是双向数据绑定触发的吗?如果是,那么您可能会在配置更改后以某种方式重新初始化UpdateIngredientViewModel中的MutableLiveData。如果没有设置断点,那么问题出在双向数据绑定上。 -
@CommonsWare 哦,我的错。我从服务器获取成分,并在每次覆盖 Livedata 的配置更改时从 ViewModel 调用该方法。谢谢你的帮助。
标签: android android-databinding android-livedata