onCheckedChanged 在初始化方法时系统调用

onCheckedChanged Systematically Called Upon Initialising Method

我有一个实现 setOnCheckedChangeListener 的 bindView 方法。但是,在初始化此方法时,会系统地调用 onCheckedChanged 方法。我怎样才能避免这种情况?这是我的代码:

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

您可以通过检查

来检查是否在按下视图后触发侦听器来避免它
buttonView.isPressed()

它将避免自动触发 checkedchange 侦听器