In one activity I have a datePicker (spinner) that allows the user select their date of birth, below that the user must also select their gender. I have a button that will be enabled once both of two values have been set (date and gender). The issue that I am facing is enabling that button despite which value is changed first. Currently, the user must select their date of birth and then their gender for the button to activate. I would like the button to be enabled regardless of which values is changed first.
Here is my code:
final RadioGroup rGroup = findViewById(R.id.gender_radio_group);
RadioButton female_radio_button = rGroup.findViewById(rGroup.getCheckedRadioButtonId());
RadioButton male_radio_button = rGroup.findViewById(rGroup.getCheckedRadioButtonId());
RadioButton non_binary_radio_button = rGroup.findViewById(rGroup.getCheckedRadioButtonId());
//Check if datePicker and gender radiobutton has been used, if true enable button
calendar.setTimeInMillis(System.currentTimeMillis());
datePicker_birthday.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
// This overrides the radiogroup onCheckListener
rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// This will get the radiobutton that has changed in its check state
RadioButton checkedRadioButton = group.findViewById(checkedId);
// This puts the value (true/false) into the variable
boolean isChecked = checkedRadioButton.isChecked();
// If the radiobutton that has changed in check state is now checked...
if (isChecked) {
continue_register_birthday_gender_button.setEnabled(true);
continue_register_birthday_gender_button.setBackground(ContextCompat.getDrawable(RegisterBirthDateAndGenderActivity.this,
R.drawable.button_active));
}
}
});
}
});
Few issues with your code.
rGroup.setOnCheckedChangeListener() would not be triggered if user chose the radio button selection first. Need to relocate outside of onDateChanged().
After relocation, it would not work too, as radiogroup listener does not know if datePicker entry is changed too.
User can choose to update gender first, followed by date or vice-versa. Possible solution as below:
Check out
fixme
for the comments.can be simplied to
because
&& isRadioGroupOnCheckedChanged
is always true because of earlier statementisRadioGroupOnCheckedChanged = true;
.