java onDateChanged和onCheckedChanged一起工作
在一个活动中,我有一个日期选择器(微调器),允许用户选择他们的出生日期,在该日期下方,用户还必须选择他们的性别。我有一个按钮,一旦两个值都设置好(日期和性别),它就会被启用。我面临的问题是启用该按钮,不管先更改哪个值。目前,用户必须先选择出生日期,然后选择性别,按钮才能激活。我希望无论先更改哪个值,都能启用该按钮
这是我的密码:
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));
}
}
});
}
});
# 1 楼答案
您的代码没有什么问题
rGroup。如果用户首先选择单选按钮,则不会触发setOnCheckedChangeListener()。 需要重新定位到onDateChanged()之外
重新定位后,它也不会工作,因为radiogroup listener不知道datePicker条目是否也发生了更改
用户可以选择先更新性别,然后更新日期,反之亦然。 可能的解决方案如下:
查看
fixme
以获得评论可以简化为
因为
&& isRadioGroupOnCheckedChanged
始终为真,因为前面的语句isRadioGroupOnCheckedChanged = true;