Android, Checkboxes Randomly Checked/Unchecked in Expandable List

前端 未结 2 1534
一个人的身影
一个人的身影 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);
        }
    

提交回复
热议问题