我上周开始学习,对书上的RadioGroup
有一些疑问。
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);
已经习惯了“获取对checkedId所指的实际对象的引用, 然后我们可以检索我们当前使用的熟悉ID 选中的单选按钮,我们现在有一个存储的引用 RB“。
我对这种解释感到非常困惑
RadioButton rb = (RadioButton) group.findViewById(checkedId);
是否必要?我试图隐藏此行并将switch (rb.getId())
更改为switch(checkedId)
,一切仍然正常。谢谢!
答案 0 :(得分:0)
不要定义radiobutton。在setOnCheckedChangeListener本身你会得到单选按钮id。移除RadioButton rb = (RadioButton) group.findViewById(checkedId);
您的代码应如下所示:
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
//}
}
});
答案 1 :(得分:0)
看到您只是更新了“tClock”,那么您对该行没有必要是正确的。如果由于某些其他原因,您需要调用任何可用的单选按钮方法。