1

我的应用程序目前针对的是 Android 1.6。它包含一个带有CHOICE_MODE_SINGLE的 ListView 。所有项目都实现Checkable。我正在使用setItemChecked(int position, boolean value)根据需要检查/取消选中项目。它可以在 Android 2.1、2.2 和 2.3 上按预期工作。然而,在 Android 1.6 上,不会检查任何项目。

代码如下所示:

Integer checkedIndex = 0; // This is actually set from somewhere else.

void updateCheckedItem() {
  int count = adapter.getCount();
  for (int i = 0; i < count; i++) {
    listView.setItemChecked(i, isChecked(i));
  }

  // Here, we should have a checked item (unless checkedIndex was null)
  SparseBooleanArray checkedPositions = listView.getCheckedItemPositions();
  int size = checkedPositions.size();
  // On Android 1.6, size is 0 (wrong)
  // On Android 2.x, size is 1 (correct)

  // Another try...
  int checkedPosition = listView.getCheckedItemPosition();
  // On Android 1.6, checkedPosition is INVALID_POSITION (-1), meaning nothing is checked (wrong)
  // On Android 2.x, checkedPosition is whatever checkedIndex is (correct)
}

boolean isChecked(int position) {
  return checkedIndex != null && checkedIndex == position;
}

这个问题通过在代码中设置 ListView 的 ChoideMode 解决了这个问题,而不是 XML。我一开始是在代码中做到这一点的,把它放在 XML 中对我来说没有任何区别。问题仍然出现。

如何在 Android 1.6 上进行这项工作?

4

2 回答 2

2

发现了问题。setItemChecked() 在 1.6 和 2.1 之间发生了变化。

当 setItemChecked() 调用值为 false 时,1.6 将始终清除选中的项目。因此,除非最后一项是选中的,否则它会以一个清除的数组结束,因此没有选中的项目。

它可以通过只为选中的项目调用 setItemChecked 来规避。取消选中其他项目(显然)由 ListView 处理。如果没有要检查的项目(checkedIndex 为空),我们应该使用clearChoices()来确保没有任何检查。这在选中的项目从列表中删除并且另一个项目占据位置的情况下很有用。如果我们不清除选择,ListView 将检查该位置,尽管 checkedIndex 为空。

void updateCheckedItem() {
  if (checkedIndex != null) {
    listView.setItemChecked(selected, true);
  } else {
    listView.clearChoices();
  }
}
于 2011-10-20T08:39:23.333 回答
0

一个问题可能出在getCheckedItemPositions()

它说:

返回列表中选中项的集合。结果仅在未设置为choice_mode_none的选择模式时才有效。

所以可能更好地使用项目点击列表器来检查项目 ID/位置。

于 2011-10-20T08:02:32.560 回答