Android, Checkboxes Randomly Checked/Unchecked in Expandable List

丶灬走出姿态 提交于 2019-12-01 10:49:16

my guess is that as your adapter is creating views, the check listener is being called as the checkbox view is initialized. a lot of widgets in android work like this ... the listener is called when the view is initialized.

i don't know why things work like this, but it might be to allow the client code to initialize itself in a consistent way. e.g., whether the checkbox is checked by the user or whether it is initialized as checked, run the same code.

to counteract this, you can try doing something like setting a flag in your listener class impl to allow you to ignore the first click, something like,

cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
    {
        private void first = true;

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (first) {
              first = false;
              return;
            }

            colors.get(groupPosition).get(childPosition).setState(isChecked);
            context.setColorBool(groupPosition, childPosition, isChecked);
            Log.d("ElistCBox2", "listitem position: " +groupPosition+"/"+childPosition+" "+isChecked);
        }
    });

also, ensure that you are correctly re-using convertView in your implementation of getView() in your adapter. e.g.,

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        view = inflater.inflate(R.layout.applications_item, null);
    }

This is a very old question, but I struggled with the same problem so here is my answer for anybody looking:

The simplest way is to use CheckBox.onClickListener instead of onCheckedChangeListener.

This is only mildly annoying in terms of rearranging your logic, but will ensure that when the boxes are unchecked randomly (by, e.g. expanding an adjacent group) the event will not fire.

Honestly I think this should be considered a bug, even though I'm sure the behaviour can be explained from the Android source.

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