I just start my learning last week, I have some questions about the RadioGroup
on my book.
radioGroup.clearCheck();
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb = (RadioButton) group.findViewById(checkedId);
switch (rb.getId()) {
case R.id.radioButtonLondon:
tClock.setTimeZone("Europe/London");
break;
case R.id.radioButtonBeijing:
tClock.setTimeZone("CST6CDT");
break;
case R.id.radioButtonNewYork:
tClock.setTimeZone("America/New_York");
break;
}
// End switch block
//}
}
});
RadioButton rb = (RadioButton) group.findViewById(checkedId);
is used to "get a reference to the actual object that checkedId is referring to, then we can retrieve the familiar ID that we use for the currently selected radio button, for which we now have a reference stored in rb."
I'm very confused about this explaination
RadioButton rb = (RadioButton) group.findViewById(checkedId);
necessary? I tried to hide this line and change switch (rb.getId())
to switch(checkedId)
and everything still working fine.Thank you!
Dont define the radiobutton.In setOnCheckedChangeListener itself you will get the radio button id.Remove RadioButton rb = (RadioButton) group.findViewById(checkedId);
Your code should look like this :
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radioButtonLondon:
tClock.setTimeZone("Europe/London");
break;
case R.id.radioButtonBeijing:
tClock.setTimeZone("CST6CDT");
break;
case R.id.radioButtonNewYork:
tClock.setTimeZone("America/New_York");
break;
}
// End switch block
//}
}
});