Is it possible to bind one ObservableField to another?

前端 未结 3 1413
星月不相逢
星月不相逢 2021-02-04 07:49

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:

3条回答
  •  梦毁少年i
    2021-02-04 08:05

    It is not possible to data bind two ObservableFields 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 ObservableFields. 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.

提交回复
热议问题