Prashant
Prashant

Reputation: 4644

CheckBox's onCheckedChanged not called after programatically changing checked state?

In my code I setOnCheckedChangeListener prior to setting initial value to CheckBox but the listener method not called after setting the initial value :

final CheckBox check_box = convertView.findViewById(R.id.check_box);

check_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 

// Some logic 
}
}

After above line, I set the initial value to CheckBox as follows,

if (isConditionTrue) {
            check_box.setChecked(true);
        } else {
            check_box.setChecked(false);
        }
}

But the listener method onCheckedChanged never called when programmatically changed the check value using method setChecked(), but when the user changes it via display it is called. Is this normal behavior or I have implemented it wrongly?

Upvotes: 4

Views: 1843

Answers (2)

chandan
chandan

Reputation: 117

Yeah its normal behavior. Because the listener is attached to the checkbox, When you change it on the application ui it will call. But if you change it programmatically, it will not execute.

Upvotes: 0

Sagar
Sagar

Reputation: 24947

setOnCheckedChangeListener() is called when the checked state of this button changes. However looking at your code, it looks like state of the checkbox might not be changing.

if (isConditionTrue) {
            check_box.setChecked(true);
        } else {
            check_box.;
        }
}

If isConditionTrue is false and check_box is already un-checked, then setChecked(false) won't result in invocation of setOnCheckedChangeListener won't be called. Same applies for check_box already checked and you try to setChecked(true);

Upvotes: 4

Related Questions