【问题标题】:onCheckedChanged Systematically Called Upon Initialising MethodonCheckedChanged 在初始化方法时系统地调用
【发布时间】:2018-05-07 19:03:07
【问题描述】:

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

【问题讨论】:

  • 谢谢阮。这确实是一个重复的问题。正如下面解决方案中的 cmets 所示,我确实看到了该解决方案,但由于我已经有了“if (isChecked)”条件,我最初认为 isPressed() 将是多余的,而实际上并非如此,之后意识到我误解了 isChecked 子句(现在正在检查......)。再次感谢你。 J

标签: android android-switch oncheckedchanged


【解决方案1】:

您可以通过检查是否在按下视图后触发侦听器来避免它

buttonView.isPressed()

它会避免自动触发checkedchange监听器

【讨论】:

  • 谢谢阿希夫。我在另一个线程上看到了该解决方案,但由于我已经有了“if (isChecked)”条件,我最初认为 isPressed() 是多余的,但实际上并非如此,在意识到我误解了isChecked 子句(现在正在检查......)。再次感谢您的宝贵时间。 J
猜你喜欢
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 2015-04-13
  • 2016-09-30
  • 2011-04-01
  • 2020-01-12
相关资源
最近更新 更多