onCheckedChanged系统地调用初始化方法

时间:2017-11-23 18:50:38

标签: android android-switch oncheckedchanged

我有一个实现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);
            }
        }
    });
}

谢谢。

Ĵ

1 个答案:

答案 0 :(得分:0)

您可以通过检查

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

它将避免自动触发checkedchange listener