这是我的代码:
<CheckBox
android:id="@+id/sprint_checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/sprint_game" />
<CheckBox
android:id="@+id/marathon_checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/marathon" />
<CheckBox
android:id="@+id/never_ending_checkbox"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/never_ending" />
我想要做的是“检测”其中一个被检查然后将另外两个设置为“禁用”,因此用户每次只能选择一个。 我试图使用“.setOnCheckedChangeListener”,但我不能这样做,有人可以帮我一些代码吗? 非常感谢你们!
答案 0 :(得分:27)
这是您收到有关已检查更改的通知的方式:
CheckBox check = findViewById(R.id.sprint_checkbox);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
}
});
您还可以让您的活动实现OnCheckedChangeListener接口,然后:
CheckBox check1 = findViewById(R.id.sprint_checkbox);
CheckBox check2 = findViewById(R.id.marathon_checkbox);
CheckBox check3 = findViewById(R.id.never_ending_checkbox);
check1.setOnCheckedChangeListener(this);
check2.setOnCheckedChangeListener(this);
check3.setOnCheckedChangeListener(this);
覆盖接口方法:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.sprint_checkbox:
//do stuff
break;
case R.id.marathon_checkbox:
//do stuff
break;
case R.id.never_ending_checkbox:
//do stuff
break;
}
}
答案 1 :(得分:1)
我相信RadioButton会更适合你的目标。
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/radio_group1">
<RadioButton
android:id="@+id/sprint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rad_option1"
android:checked="true"
android:onClick="onRadioButtonClick"
/>
<RadioButton
android:id="@+id/marathon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rad_option2"
android:onClick="onRadioButtonClick"
/>
<RadioButton
android:id="@+id/neverending"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/rad_option3"
android:onClick="onRadioButtonClick"
/>
</RadioGroup>
然后在你的代码中:
public void onRadioButtonClick(View v) {
RadioButton button = (RadioButton) v;
// DO YOUR THING HERE DEPENDING ON WHICH RADIOBUTTON IS PICKED
}
在这种情况下,您不必处理禁用其他选项的问题。默认情况下,用户只能选择一个选项。
答案 2 :(得分:1)
extend
这应该允许你使用ID。希望它有效。