0
我有一個listView與複選框和列表中的第一個複選框是一個選擇/取消選擇所有複選框。Android的錯誤行爲爲列表視圖選擇/取消選擇所有複選框操作
List<CheckedItem> items = new ArrayList<CheckedItem>();
// items.add(new CheckedItem(getResources().getString(R.string.select_all),getResources().getString(R.string.select_all)));
adapter = new DownloadDocsListViewAdapter(getContext(), items);
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
SparseBooleanArray sparseArray = adapter.getBooleanArray();
isAtLeastOneElementChecked = false;
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
boolean obj = sparseArray.get(key);
if (i == 0) {
for (int j=0; j < listView.getAdapter().getCount(); j++) {
CheckedItem checkedItem = (CheckedItem) listView.getAdapter().getItem(i);
checkedItem.setChecked(obj);
}
}
if (obj == true) {
isAtLeastOneElementChecked = true;
break;
}
}
getActivity().invalidateOptionsMenu();
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
//add the select All checkbox
adapter.add(new CheckedItem(getResources().getString(R.string.select_all),getResources().getString(R.string.select_all)));
這是清單
public class DownloadDocsListViewAdapter extends ArrayAdapter<CheckedItem> implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray booleanArray = new SparseBooleanArray();
public DownloadDocsListViewAdapter(Context context, List<CheckedItem> objects) {
super(context, R.layout.generated_multiple_docs_item, objects);
for (CheckedItem checkedItem : objects) {
objects.add(checkedItem);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
CheckedItem item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.download_docs_item, parent, false);
}
// Populate the data into the template view using the data object
TextView tvName = (TextView) convertView.findViewById(R.id.itemTextId);
tvName.setText(item.getValue());
CheckBox checkBoxView = (CheckBox) convertView.findViewById(R.id.checkBoxViewId);
checkBoxView.setOnCheckedChangeListener(this);
checkBoxView.setTag(position);
return convertView;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = Integer.parseInt(buttonView.getTag().toString());
CheckedItem item = getItem(position);
booleanArray.put(position, isChecked);
item.setChecked(isChecked);
notifyDataSetChanged();
}
public SparseBooleanArray getBooleanArray() {
return booleanArray;
}
}
ListView的複選框狀態改變的適配器,但列表視圖元素不會出現選中或取消選中。