Android, Checkboxes Randomly Checked/Unchecked in Expandable List

前端 未结 2 1531
一个人的身影
一个人的身影 2021-01-15 03:16

Using this Expandable List checkbox example code as an baseline, I am trying to save and maintain the checkbox state. However, random checkboxes are being checked and unchec

相关标签:
2条回答
  • 2021-01-15 03:54

    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);
        }
    
    0 讨论(0)
  • 2021-01-15 04:12

    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.

    0 讨论(0)
提交回复
热议问题