I understand that the purpose of Android\'s data-binding library is for views to observe data and automatically update when that data changes.
Question:
It is not possible to data bind two ObservableField
s using binding syntax in Android data binding. However, you can bind them with code:
class RegisterViewModel {
public final ObservableField username = new ObservableField<>();
public final ObservableField password = new ObservableField<>();
public final ObservableField confirmPassword = new ObservableField<>();
public final ObservableBoolean isValid = new ObservableBoolean();
private boolean isUsernameValid;
private boolean isPasswordValid;
private boolean arePasswordsSame;
public RegisterViewModel() {
// You can use 3 different callbacks, but I'll use just one here
// with 'if' statements -- it will save allocating 2 Object.
OnPropertyChangedCallback callback = new OnPropertyChangedCallback() {
@Override
public void onPropertyChanged(Observable sender, int propertyId) {
if (sender == username) {
isUsernameValid = ValidationUtils.validateUsername(name);
} else if (sender == password) {
isPasswordValid = ValidationUtils.validatePassword(pwd);
} else if (sender == confirmPassword) {
arePasswordsSame = password.get()
.equalsIgnoreCase(confirmPassword.get());
} else {
// shouldn't get here...
}
isValid.set(isUsernameValid && isPasswordValid && arePasswordsSame);
}
};
username.addOnPropertyChangedCallback(callback);
password.addOnPropertyChangedCallback(callback);
confirmPassword.addOnPropertyChangedCallback(callback);
}
}
Here, I've assumed that empty username, password, and confirmPassword are invalid. Seemed a safe assumption.
I don't see a tremendous need for private ObservableField
s. ObservableField
was designed to be bound to by the UI and if you can't, you can use other data types. If you find them useful for internal binding using callbacks like the above, then go for it.