投稿 资料上传 提问 搜索
您现在的位置是: 首页 > 问答 > 正文

android的CheckBox点击全选信息反馈不正常,该如何解决

点击全选,反馈的信息是没有,而取消全选反而反馈全了,为什么会这样?该如何解决  


代码如下:

public class CheckBoxActivity extends AppCompatActivity {

private CheckBox eatCheckBox,sheepCheckBox,gameCheckBox,allCheckBox;
private Button button;
private TextView textView1,textView2;

private CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String resultString = "";
if (eatCheckBox.isChecked()) {
resultString+=eatCheckBox.getText().toString()+" ";
}
if (sheepCheckBox.isChecked()) {
resultString+=sheepCheckBox.getText().toString()+" ";
}
if (gameCheckBox.isChecked()) {
resultString+=gameCheckBox.getText().toString()+" ";
}
if (buttonView.getId()==R.id.allCb) {
if(allCheckBox.isChecked()){
eatCheckBox.setChecked(true);
sheepCheckBox.setChecked(true);
gameCheckBox.setChecked(true);
}
else if(eatCheckBox.isChecked()&&sheepCheckBox.isChecked()&&gameCheckBox.isChecked()){
eatCheckBox.setChecked(false);
sheepCheckBox.setChecked(false);
gameCheckBox.setChecked(false);
}
}
else{
if(eatCheckBox.isChecked()&&sheepCheckBox.isChecked()&&gameCheckBox.isChecked()){
allCheckBox.setChecked(true);
}
else{
allCheckBox.setChecked(false);
}
}
textView1.setText("你的爱好是:"+resultString);
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);

eatCheckBox=findViewById(R.id.eatCb);
sheepCheckBox=findViewById(R.id.sheepCb);
gameCheckBox=findViewById(R.id.gameCb);
allCheckBox=findViewById(R.id.allCb);
button=findViewById(R.id.btn);
textView1=findViewById(R.id.tv1);
textView2=findViewById(R.id.tv2);

eatCheckBox.setOnCheckedChangeListener(listener);
sheepCheckBox.setOnCheckedChangeListener(listener);
gameCheckBox.setOnCheckedChangeListener(listener);
allCheckBox.setOnCheckedChangeListener(listener);
}
}


问题回复
  1. 浅若夏沫ン
    浅若夏沫ンIT技术之家

    首先你的resultString不应该定义在check事件中,应该定义在外面,然后在每次check事件改变时清空resultString的内容,代码如下:  


    回复