如何使用 Android 数据绑定从 UI 更新对象?

How to update an object from the UI with Android Data Binding?

我正在使用数据绑定并且创建了一个非常简单的 class

public class ViewUser extends BaseObservable {
    private String name;

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }
}

布局简单

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
        <variable
            name="user"
            type="com.example.ViewUser" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="top"
                    android:lines="3"
                    android:text="@{user.name}" />
    </LinearLayout>
</layout>

当我更新对象时,UI 更新没有任何问题,但是如果我从 UI 更改 EditText 的值,然后使用 DataBindingUtil .getUser() 获取用户, 它没有更新的值。是否可以让 属性 自动更新,或者我是否必须使用像 TextWatcher 的 onTextChanged 这样的事件来更新对象?

您的 xml 标签 android:text@ 之后缺少 = android:text="@={user.name}"

@={}表示"two way data binding"。 @{} 是一种数据绑定方式。

用于从您的 XML 设置和获取更新的模型。您必须在 Edittext 中执行此操作:

来自:

android:text="@{user.name}"

至:

 android:text="@={user.name}"

编码愉快!!