我有一个使用 listview 的 android 应用程序。每一行都由 ImageView、一个 TextView 和一个 CheckBox 组成。 我想从此 ListView 中获取选定的项目。我使用了
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();
}
}
});
关于android - 如何从android listview中获取选中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110724/