数据绑定仅在双向绑定模型上执行一次

时间:2017-09-19 02:33:02

标签: android

我有以下EditText布局。

            <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            app:hintTextAppearance="@{ android.util.Patterns.EMAIL_ADDRESS.matcher(account.email).matches()? com.mdsf.R.style.MNS_TextAppearance_Hint : com.mdsf.R.style.MNS_TextAppearance_Hint_Error}"
            android:layout_height="50dp"
            android:visibility="@{android.util.Patterns.EMAIL_ADDRESS.matcher(account.email).matches()? View.GONE : View.VISIBLE}">
            <android.support.design.widget.TextInputEditText
                android:inputType="textEmailAddress"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="@={account.email}"
                style="@style/MnsEditText"
                android:hint="Email"/>

我的问题是,当hintTextAppearance通过双重绑定进行更改时,account.email的databinidng不会重新执行。我已确认email文字属性正在更新帐户的EditText媒体资源。这是我的帐户模型,这里也是活动:

public class Account extends BaseObservable {

public int id;
public int mediaId;
public String firstName;
public String lastName;
public String email ="";
public String password;
public String addressLine1;
public String addressLine2;
public String city;
public String region;
public String phone;
public String gender;
public String postalCode;

public boolean isSetUp;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@Bindable
public int getMediaId() {
    return mediaId;
}

public void setMediaId(int mediaId) {
    this.mediaId = mediaId;
}

@Bindable
public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

@Bindable
public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

@Bindable
public String getEmail() {
    return email;
}

我设置了一个断点,我发现在添加或更改绑定到getEmail的文本时,永远不会调用account.email

最后,这是我的布局资源开头的<data>标记:

<data>

    <variable
        name="account"
        type="com.msdf.network.model.Account" />
 </data>

最后是我的Account活动

public class CreateAccountActivity extends BaseTabBarActivity {
private Account account;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityCreateAccountBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_create_account);
    account = new Account();
    //account.setEmail("gig@c.com");
    binding.setAccount(account);
}
}

1 个答案:

答案 0 :(得分:1)

我的问题在阅读this excellent resource之后,在我意识到我省略了DataBinding设置的一个非常重要的部分之后就解决了。也就是说,对于account.email属性的setter,我没有写

public void setEmail(String email){
  this.email = email;
  notifiyPropertyChanged(BR.email); //This line was omitted
}

因此,即使双向绑定对我的TextEditField起作用,它也没有通知模型email已更改,因此绑定到account.email的任何内容都没有更新它已更改,即使它已成功写入。