Select 所有 ListViewItem 的 CheckBox

Select CheckBox of all ListViewItem

我得到了一个 ListActivity,其中包含我创建的列表项。每个项目都有一个 CheckBox 。此外,布局有一个按钮,它应该只是检查所有复选框,但即使调用按钮的 OnClickListener 它也不起作用。

这是从列表适配器调用的方法:

    public void ChangeAllCheckStatus(boolean checked)
    {
        synchronized (items)
        {
            for (ItemData item : items)
            {
                item.checked= checked;
            }
        }
        notifyDataSetChanged();
    }

这是 getView 方法:

@Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View vi = convertView;
        if (vi == null)
        {
            vi = m_inflater.inflate(R.layout.myItem, null);
        }
        TextView nameTextView = (TextView) vi.findViewById(R.id.firstText);
        TextView addressTextView = (TextView) vi.findViewById(R.id.secondText);
        CheckBox cb = (CheckBox) vi.findViewById(R.id.the_checkBox);
        nameTextView.setText(items.get(position).string1);
        addressTextView.setText(items.get(position).string2);
        cb.setSelected(items.get(position).checked);
        return vi;
    }

我尝试选中所有复选框的方式有问题吗?

您没有从适配器获取视图。 ListView 就是这样做的。

相反,您可以像这样通过 ListView 循环播放它们:

ListView lv;
int itemCount = lv.getCount();
for (int i=0; i<itemCount; ++i) {
    CheckBox cb = (CheckBox) lv.getChildAt(i).findViewById(R.id.the_checkBox);
    cb.setChecked(true);
}
 listItem = myList.getAdapter().getView(i, null, null);

错了。您不应该直接访问 ListView 的项目。您应该封装数据集中每个项目的检查状态,并让 getView 发挥作用。

假设您在 ListView 的项目中有一个 boolean status; 成员,您可以在适配器中添加一个方法,

public void checkAll() {
  synchronized(items) {
    for (Item item : items) {
       item.status = true;
    }
  }
  notifyDataSetChanged();
}

编辑:

It got an adapter which extends BaseAdapter which also receives 2 arrays of strings as the values. It creates the view at a specific position simply by setting 2 text boxes with the corresponding values from these 2 arrays.

您可以使用一个小的 class 来封装您需要的信息,而不是使用两个数组。例如

public class Item {
  public String mFirstString; 
  public String mSecondString;  
  public boolean mStatus;
} 

并向 BaseAdapter 提供此 class 的集合。例如

ArrayList<Item> mItems = new ArrayList<>();

getItem 将 return mItem.get(position),在 getView 上您将设置文本和复选框。例如

 Item item = getItem(position);
 CheckBox cb = (CheckBox) rootView.findViewById(R.id.the_checkBox);
 cb.setChecked(item.mStatus);