Android CheckBox - Removing a previously setOnCheckedChangeListener

会有一股神秘感。 提交于 2019-12-01 21:02:56

问题


I have an application that displays a ListView using a CursorAdapter that I have customized. Within my custom CursorAdapter.bindView, I have a CheckBox object that I set the checked value (based on a column on the cursor) and set a clickListener. Here is my code:

    CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.list_done);
    mCheckBox.setChecked(isDone);
    mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
                AW.getDB().updateTask(c.getInt(c.getColumnIndex(ToDoDBAdapter.KEY_ID)), isChecked);
                TD.displayTasks();
        }
    });

The only problem is that when Android recycles my views, the onCheckedChangeListener is still active, and thus the call to setChecked() causes that code within the listener to run. I would like to know how to invalidata the onCheckedChangedListener right before the code I have included runs.


回答1:


You can do something like:

// c is the Cursor you are getting
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.list_done);
mCheckBox.setTag(new Integer(c.getPosition());
mCheckBox.setChecked(isDone);
mCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        Integer posInt = (Integer)buttonView.getTag();

        int pos = posInt.intValue();
        c.moveToPosition(pos);
            AW.getDB().updateTask(c.getInt(c.getColumnIndex(ToDoDBAdapter.KEY_ID)), isChecked);
            TD.displayTasks();
    }
});

There are lots of optimizations you can do to above code. I just illustrated the basic logic.




回答2:


You can call mcheckBox.setOnCheckedChangeListener(null); if it is done inside the onCheckedChangeListener, you need to declare mCheckBox final.



来源:https://stackoverflow.com/questions/8549214/android-checkbox-removing-a-previously-setoncheckedchangelistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!