【发布时间】: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所暗示的那样)。 -
双向数据绑定已添加到 Android Studio 2.1 预览版中。看看这个博客:halfthought.wordpress.com/2016/03/23/…
-
如何在活动中访问更新的模型。很想看看你的活动。
标签: android data-binding bidirectional 2-way-object-databinding android-databinding