@Gober android 数据绑定支持两种方式绑定。因此,您无需手动制作。正如您尝试将 OnTextChanged-listener 放在 editText 上一样。它应该更新模型。
我尝试在 editText 上放置一个 OnTextChanged-listener 并更新模型。这创建了一个循环杀死我的应用程序(模型更新更新 GUI,它调用 textChanged 时间无穷大)。
值得注意的是,实现双向绑定的绑定框架通常会为您执行此检查……</p>
这是修改后的视图模型的示例,如果更改源自观察者,则不会引发数据绑定通知:
让我们创建一个只需要重写一个方法的 SimpleTextWatcher:
public abstract class SimpleTextWatcher implements TextWatcher {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
onTextChanged(s.toString());
}
public abstract void onTextChanged(String newValue);
}
接下来,在视图模型中,我们可以创建一个公开观察者的方法。观察者将被配置为将控件的更改值传递给视图模型:
@Bindable
public TextWatcher getOnUsernameChanged() {
return new SimpleTextWatcher() {
@Override
public void onTextChanged(String newValue) {
setUsername(newValue);
}
};
}
最后,在视图中,我们可以使用 addTextChangeListener 将观察者绑定到 EditText:
<!-- most attributes removed -->
<EditText
android:id="@+id/input_username"
android:addTextChangedListener="@{viewModel.onUsernameChanged}"/>
这是解决通知无穷大的视图模型的实现。
public class LoginViewModel extends BaseObservable {
private String username;
private String password;
private boolean isInNotification = false;
private Command loginCommand;
public LoginViewModel(){
loginCommand = new Command() {
@Override
public void onExecute() {
Log.d("db", String.format("username=%s;password=%s", username, password));
}
};
}
@Bindable
public String getUsername() {
return this.username;
}
@Bindable
public String getPassword() {
return this.password;
}
public Command getLoginCommand() { return loginCommand; }
public void setUsername(String username) {
this.username = username;
if (!isInNotification)
notifyPropertyChanged(com.petermajor.databinding.BR.username);
}
public void setPassword(String password) {
this.password = password;
if (!isInNotification)
notifyPropertyChanged(com.petermajor.databinding.BR.password);
}
@Bindable
public TextWatcher getOnUsernameChanged() {
return new SimpleTextWatcher() {
@Override
public void onTextChanged(String newValue) {
isInNotification = true;
setUsername(newValue);
isInNotification = false;
}
};
}
@Bindable
public TextWatcher getOnPasswordChanged() {
return new SimpleTextWatcher() {
@Override
public void onTextChanged(String newValue) {
isInNotification = true;
setPassword(newValue);
isInNotification = false;
}
};
}
}
我希望这是您正在寻找的,并且肯定可以帮助您。谢谢