mardi 4 septembre 2018

Android : multiple checkboxes get/set status to use RxBinding

First, I apologize my bad English skill.

I have 5 checkboxes, and use RxBinding to check all checkboxes status.

expect logic (var name starts with 'cb' is Checkboxes, starts with 'btn' is Button)

  1. If check/uncheck cbAgreeAll, then cbOption1~cbOption4 set the same status with cbAgreeAll.
  2. If cbOption1~cbOption4 all checked, then cbAgreeAll is also set check.
  3. If one or more checkboxes are unchecked, then cbAgreeAll is also set uncheck.
  4. If cbOption1, cbOption2 is checked, then btnNext Button setEnabled(true)

1st and 2nd logic worked like what I expected, but when all checkboxes are checked, and I uncheck one of cbOption1~cbOption4, then all the checkboxes are uncheked. and 4 is also didn't worked. I worried about this question for a day, but didn't find the answer yet.

My codes like below,

Disposable cbAgreeallDisposable = RxCompoundButton.checkedChanges(binding.cbAgreeall).subscribe(check -> {
        isAllAgree = check;
        binding.cbOption1.setChecked(check);
        binding.cbOption2.setChecked(check);
        binding.cbOption3.setChecked(check);
        binding.cbOption4.setChecked(check);
    });
    Observable<Boolean> cbOption1 = RxCompoundButton.checkedChanges(binding.cbOption1);
    Observable<Boolean> cbOption2 = RxCompoundButton.checkedChanges(binding.cbOption2);
    Observable<Boolean> cbOption3 = RxCompoundButton.checkedChanges(binding.cbOption3);
    Observable<Boolean> cbOption4 = RxCompoundButton.checkedChanges(binding.cbOption4);


    compositeDisposable.add(cbAgreeallDisposable);
    compositeDisposable.add(cbOption1.subscribe(check -> isOption1Agree = check));
    compositeDisposable.add(cbOption2.subscribe(check -> isOption2Agree = check));
    compositeDisposable.add(cbOption3.subscribe(check -> isOption3Agree = check));
    compositeDisposable.add(cbOption4.subscribe(check -> isOption4Agree = check));

    compositeDisposable.add(Observable
            .combineLatest(cbOption1, cbOption2,
                    (cb1, cb2) -> cb1 && cb2)
            .subscribe(isValid -> binding.btnNext.setEnabled(isValid))
    );

    compositeDisposable.add(Observable
            .combineLatest(cbOption1, cbOption2, cbOption3, cbOption4,
                    (cb1, cb2, cb3, cb4) -> cb1 && cb2 && cb3 && cb4)
            .subscribe(isValid -> binding.cbAgreeall.setChecked(isValid)
    ));

Thanks to see my question.




Aucun commentaire:

Enregistrer un commentaire