android - 如何使用 Android 数据绑定(bind)从 UI 更新对象?

标签 android data-binding bidirectional 2-way-object-databinding android-databinding

我正在使用数据绑定(bind)并创建了一个非常简单的类

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

@={} 表示“双向数据绑定(bind)”。 @{} 是一种数据绑定(bind)方式。

关于android - 如何使用 Android 数据绑定(bind)从 UI 更新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36337039/

相关文章:

c - 如何使用单独的进程但不 fork 地读取/写入 Linux 伪终端?

java - Hibernate OneToMany 双向关系很慢

http2 - 关于 http/2 的文章中有关双向和全双工的混淆

Android如何将对象用户传递给 Activity fragment

php - 获取具有相同值同表的SQL数据

java - 使用 Swing 在 GUI 中显示类内容

xaml - UWP ListView DataTemplate 绑定(bind)到项目而不是属性

javascript - 如何通过代理从代码中更新对象的属性来更新输入的值?

java - 在android中通过libmedia播放加密视频

java - Android 6.0 运行时异常 : Fail to connect to camera service