【问题标题】:How to update an object from the UI with Android Data Binding?如何使用 Android 数据绑定从 UI 更新对象?
【发布时间】:2016-03-31 14:59:07
【问题描述】:

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

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 之类的事件来更新对象?

【问题讨论】:

  • AFAIK,您必须自己处理。例如,在这种情况下,如果数据绑定执行了您想要的操作,那么您将面临无限循环的风险(EditText 调用 setUser() 表示模型已更改,导致数据绑定更新调用 @987654328 的 EditText @ 哪一个...)。另请记住,您需要选择加入,因为不是每个人都希望在每次击键的基础上更新他们的模型(正如您使用 TextWatcher 所暗示的那样)。
  • 这可能会有所帮助:stackoverflow.com/questions/33362533/…
  • 双向数据绑定已添加到 Android Studio 2.1 预览版中。看看这个博客:halfthought.wordpress.com/2016/03/23/…
  • 如何在活动中访问更新的模型。很想看看你的活动。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    来自:

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

    到:

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

    编码愉快!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多