LiveData特定属性的两种数据绑定object

Two way data binding of specific attribute of LiveData object

我在使用 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}" 初始化 Ingredient 的标题值,但是如果我更改 EditText 中的文本并旋转显示,例如,我没有得到更改的值,但是初始化的那个。有人可以帮我吗? 这是我的视图模型:

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);
    }
}

编辑

这是原料 class:

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;
    }
}

我也试过像这样更改 EditText 属性 android:text="@={viewModel.ingredient.title}",但它的工作方式似乎与原始 post.

相同

双向数据绑定可以更新您的模型。但是,您的方法有两个问题。

你运行进入的那个是MutableLiveData不是魔法,如果你替换值,它会很乐意执行命令。基于 ,您在配置更改后替换了 MutableLiveData 中的值,而这并没有考虑用户输入的内容。

另一个问题是,虽然 MutableLiveData 将保留您修改后的 Ingredient,但 MutableLiveData 的任何其他观察者都不知道该更改。您正在 原地 修改模型,而 MutableLiveData 不知道并且不能让其他观察者知道。这就是为什么我更喜欢使用尽可能不可变的 MutableLiveData 对象(例如,Kotlin val),因此我跳过了双向数据绑定。