双向数据绑定

时间:2018-10-21 12:10:18

标签: android xml android-databinding

我对双向数据bindig有问题。这是我的课程:

public class User extends BaseObservable {
private String name;
private String surname;
private Address address;

public User() {
}

public User(String name, String surname) {
    this.name = name;
    this.surname = surname;
}

@Bindable
public Address getAddress() {
    return address;
}

public void setAddress(Address address) {
    this.address = address;
    notifyPropertyChanged(BR.address);
}

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

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

@Bindable
public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
    notifyPropertyChanged(BR.surname);
}
}

public class Address extends BaseObservable {
private String name;

public Address(String name) {
    this.name = name;
}

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

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

我正在尝试将用户绑定到xml文件中,但是我也想绑定地址名称。不幸的是,当我使用address.setName(“ abc”)时,我的UI不变。我在地址设置器中使用notifyPropertyChanged(BR.address),但没有帮助。可以那样做吗?这是我的xml文件的摘要:

    <data>
            <variable name="user" type="com.rolnik.test.User"/>
        </data>

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

1 个答案:

答案 0 :(得分:0)

好,我解决了这个问题。我将notifyPropertyChanged(BR.name)放在地址设置器中并重建项目。没有最后一个就行不通。