@George Mount是正确的,您必须在您的模型或处理程序类(无论您称之为)中定义的布局xml中添加处理程序。
看看我的回答对这个问题的一个羽翼丰满的例子:
Two way databinding with Android Databinding Library
下面是这个问题的答案的例子:
例子:
public class AmanteEditModel extends BaseObservable {
private String senhaConfirm;
@Bindable
public String getSenhaConfirm() {
return senhaConfirm;
}
public void setSenhaConfirm(String senhaConfirm) {
this.senhaConfirm = senhaConfirm;
notifyPropertyChanged(BR.senhaConfirm);
}
// Textwatcher Reference: http://developer.android.com/reference/android/text/TextWatcher.html
public TextWatcher getMyEditTextWatcher() {
return new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// Important! Use the property setter, otherwhise the model won't be informed about the change.
setSenhaConfirm(s);
}
};
}
}
在布局XML将EditText更改为:
<EditText
android:id="@+id/amante_edit_senha_confirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:hint="Confirme a senha"
android:inputType="textPassword"
android:maxLines="1"
android:text="@{model.senhaConfirm}"
app:addTextChangeListener="@{model.myEditTextWatcher}"
/>
请注意名称空间为addTextChangeListener。此方法可能无法通过android:命名空间获得,所以我正在使用app:here。您也可以使用bind:使绑定更清晰。
所以千万不要错过
xmlns:app="http://schemas.android.com/apk/res-auto"
或
xmlns:bind="http://schemas.android.com/apk/res-auto"
添加到您的XML命名空间。
此解决方案适用于所有输入控件,包含自定义,因为您在模型中提供了正确的听众。
TextWatcher Reference
嗯,它应该工作。它可能是一个IDE突出的错误。你尝试编译? – yigit
今天我学到了,我应该总是试着编译:)它的工作原理!谢谢,yigit! – prograde
但是,嗯,它会调用foo.getBar()方法将它自己设置在正确的位置。但它似乎永远不会调用foo.setBar()方法,所以在我的代码中永远不会更新该值。它仍然需要一个SeekBarChangeListener,或者什么? – prograde