据我了解,要判断一个复选框是否被“点击”并判断它是否被选中,可以使用如下代码:
cb=(CheckBox)findViewById(R.id.chkBox1);
cb.setOnCheckedChangeListener(this);
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
cb.setText("This checkbox is: checked");
}
else {
cb.setText("This checkbox is: unchecked");
}
}
但是,我无法弄清楚如何为 radio 组执行上述操作的逻辑。
这是我的 RadioGroup 的 xml:
<RadioGroup android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio1" android:checked="true"
android:text="RadioButton1">
</RadioButton>
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio2" android:text="RadioButton2" android:checked="true">
</RadioButton>
<RadioButton android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radio3" android:text="RadioButton3">
</RadioButton>
</RadioGroup>
问题:我是否需要设置另一个监听器,或者已经存在的监听器也会“注册”这个组?
另外,监听器应该设置在 RadioGroup 还是 RadioButton 上?
最佳答案
这是您获得选中单选按钮的方式:
// This will get the radiogroup
RadioGroup rGroup = (RadioGroup)findViewById(r.id.radioGroup1);
// This will get the radiobutton in the radiogroup that is checked
RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());
要使用监听器,请执行以下操作:
// 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 = (RadioButton)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)
{
// Changes the textview's text to "Checked: example radiobutton text"
tv.setText("Checked:" + checkedRadioButton.getText());
}
}
});
关于Android:RadioGroup - 如何配置事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6780981/