Can't change background color of CheckBox view twice - Android

后端 未结 2 1952
北恋
北恋 2021-01-27 12:50

I try to change CheckBox background after user change its state to Checked. Code below doesn\'t work quite well. If i click unchecked checkbox

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-27 13:55

    For it to change when checked you need to attach an OnCheckChangedListener. Then place the above code inside that.

    CheckBox tmpChkBox = (CheckBox) findViewById(view.getId());
    tmpChkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setBackgroundColor(Color.BLUE);
            } else { 
                buttonView.setBackgroundColor(Color.RED);
            }
        }
     });
    

提交回复
热议问题