androidandroid-switchoncheckedchanged

onCheckedChanged Systematically Called Upon Initialising Method


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);
            }
        }
    });
}

Solution

  • 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