little_1999
2020-03-24 00:52
采纳率: 50%
浏览 213

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条回答 默认 最新

  • 代码的灵魂是bug! 2020-03-24 10:27
    已采纳

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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题