0

I have a bindView Method which implements setOnCheckedChangeListener. However, upon initializing this Method, the onCheckedChanged Method is systematically called. How could I avoid this? Here is my code:

public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);
    
    alarm_activation = cursor.getColumnIndexOrThrow(mydb.ALARMS_ACTIVATED);
    activationInt = cursor.getInt(alarm_activation);
    alarm_id_ind = cursor.getColumnIndexOrThrow("rowid");
    alarm_id_int = cursor.getInt(alarm_id_ind);
    StrLog = String.valueOf(alarm_id_int);

    Log.e("Row ID", StrLog);
    alarm_activated = (ToggleButton)view.findViewById(R.id.alarm_activated);
    alarm_activated.setTag(alarm_id_int);

    if (activationInt == 1) {
        alarm_activated.setChecked(true);
        alarm_activated.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
        activateAlarm(alarm_id_int);
    } else {
        alarm_activated.setChecked(false);
    }

    alarm_activated.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);
                row = (Integer) buttonView.getTag();
                mydb.activateAlarm(row);
                activateAlarm(alarm_id_int);
            } else {
                buttonView.getBackground().setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                row = (Integer) buttonView.getTag();
                mydb.deactivateAlarm(row);
            }
        }
    });
}
user229044
  • 232,980
  • 40
  • 330
  • 338
JF0001
  • 819
  • 7
  • 30
  • 3
    Possible duplicate of [onCheckedChanged called automatically](https://stackoverflow.com/questions/27641705/oncheckedchanged-called-automatically) – Ruan_Lopes Nov 23 '17 at 18:57
  • Thank you Ruan. This is indeed a duplicate question. As indicated in my comments in the solution below, I had indeed seen that solution, but since I already had an "if (isChecked)" condition, I initially thought that isPressed() would be redundant, while it actually isn't, after realizing that I was mis-interpreting the isChecked clause (as being checked now...). Thank you again. J – JF0001 Nov 24 '17 at 15:14

1 Answers1

1

You can avoid it by checking that listener is triggered after your view is pressed or not by checking

buttonView.isPressed()

It will avoid auto triggering checkedchange listener

demo_Ashif
  • 316
  • 4
  • 10
  • Thank you Ashif. I had seen that solution on another thread, but since I already had an "if (isChecked)" condition, I initially thought that isPressed() would be redundant, while it actually isn't, after realizing that I was mis-interpreting the isChecked clause (as being checked now...). Thank you again for your time. J – JF0001 Nov 24 '17 at 15:11