首页 > 解决方案 > 如何使用带扩展列表视图的全选复选框?

问题描述

这是我设置子视图的代码。我将第一个子项设置为全选布局,然后将子项的布局设置为其余部分。当我按下全选复选框时,没有任何反应。

public View getChildView(int groupPosition, final int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            ArrayList<CheckBox> myCheckBoxes = new ArrayList<>();

            if(childPosition == 0){
                convertView = inflater.inflate(R.layout.child_header, null);
                chkBoxselectAll = convertView.findViewById(R.id.chk_select_all);

            } else {
                convertView = inflater.inflate(R.layout.child_row, null);
                chkBoxsurvey = convertView.findViewById(R.id.chk_survey);
                for (int i = 0; i < parent.getChildCount(); i++) {
                    View v = parent.getChildAt(i);
                        if(v.getId() == (R.id.chk_survey))
                            myCheckBoxes.add((CheckBox)v.findViewById(R.id.chk_survey));
                }
            }
 if (childPosition > 0 && childPosition < getChildrenCount(groupPosition) - 1) {

            chkBoxselectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {

                    for (int i = 0; i < myCheckBoxes.size(); i++) {
                        if(isChecked)
                            myCheckBoxes.get(i).setChecked(true);
                        else
                            myCheckBoxes.get(i).setChecked(false);
                    }
    }
            return convertView;
        }

标签: javaandroidandroid-checkboxselectall

解决方案


我没有看到任何通知您的列表的声明,因此您需要为此添加行。

见下面的代码,我添加了notifyDataSetChanged出侧循环

  for (int i = 0; i < myCheckBoxes.size(); i++) {
     if(isChecked)
        myCheckBoxes.get(i).setChecked(true);
     else
        myCheckBoxes.get(i).setChecked(false);
   }
   notifyDataSetChanged();

推荐阅读