OnCheckedChangeListener and why it is always executed?

I have a list item layout containing a textview and a checkbox which will be rendered in a listview. The thing i wanted to happen is when a user selects a checkbox an item from an array of objects with the relevant id will be marked as checked.

But my problem was that the OnCheckedChangeListener was always called when i set the initial state of the checkbox. That means if I have:

 
holder.tbNotification.setChecked(notification.isAllowed());
holder.tbNotification.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {});

the listener will again be called even if it is declared after the checked state.

So the answer is to set the listener to NULL, change the checkbox state and set the new listener.


holder.tbNotification.setOnCheckedChangeListener(null);
holder.tbNotification.setChecked(notification.isAllowed());
holder.tbNotification.setSelected(notification.isAllowed());
holder.tvNotificationTitle.setText(notification.getLabel());
holder.tbNotification.setTag(position);
if (notification.getType().equals("0")) {
disableRow = notification;
if (disableRow.isAllowed() == false) {
shouldDisableAll = true;
}
holder.tvNotificationTitle.setPadding(10, 0, 0, 0);
holder.tbNotification
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {});

You may also like...