尝试在不使用RadioGroup
的情况下处理RadioButtons
。
将各个RadioButtons
连接起来并将它们保存在一个ArrayList<RadioButton>
中。
List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add( (RadioButton)findViewById(R.id.button1) );
radioButtons.add( (RadioButton)findViewById(R.id.button2) );
radioButtons.add( (RadioButton)findViewById(R.id.button3) );
etc.
为每个 RadioButton
设置一个 OnCheckedChangeListener
。
for (RadioButton button : radioButtons){
button.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) processRadioButtonClick(buttonView);
}
});
}
接着创建一个方法来取消选中未选择的RadioButtons
。
private void processRadioButtonClick(CompoundButton buttonView){
for (RadioButton button : radioButtons){
if (button != buttonView ) button.setChecked(false);
}
}
使用这种方法,RadioButtons
可以放置在XML布局的任何位置。