这是我的代码:
<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”,但我不能那样做,有人可以帮我写一些代码吗? 非常感谢你们!
最佳答案
这是通知您已检查更改的方式:
CheckBox check = findViewById(R.id.sprint_checkbox);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
}
});
您还可以让您的 Activity 实现 OnCheckedChangeListener 接口(interface),然后:
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);
重写接口(interface)方法:
@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;
}
}
关于android - 当复选框改变状态时如何做某事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332111/