我有一个android应用程序,它使用listview,每一行由imageview、textview和一个复选框组成。
我想从这个列表视图中获取选定的项目。我使用
private void getSelectedItems() {
List<String>list = new ArrayList<String>();
try {
SparseBooleanArray checkedItems = new SparseBooleanArray();
checkedItems = listView.getCheckedItemPositions();
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
int position = checkedItems.keyAt(i);
boolean bool = checkedItems.valueAt(position);
if (bool) {
list.add(mainList.get(position));
}
}
} catch (Exception e) {
}
}
但我想在启动时将某些项设置为与条件相关的已检查项。仅当用户选中/取消选中某个项时,才获取选中项。即使在启动时以编程方式将该项设置为已检查,也不会获取选中项。这里有什么问题?
提前谢谢
最佳答案
做这样的事,
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
myListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
CheckBox cb = (CheckBox) view.findViewById(R.id.yourCheckBox);
Toast.makeText(getApplicationContext(), "Row " + position + " is checked", Toast.LENGTH_SHORT).show();
if (cb.isChecked()) {
checkedPositions.add(position); // add position of the row
// when checkbox is checked
} else {
checkedPositions.remove(position); // remove the position when the
// checkbox is unchecked
Toast.makeText(getApplicationContext(), "Row " + position + " is unchecked", Toast.LENGTH_SHORT).show();
}
}
});