我有一个已启用多项选择的列表,我需要获取所选的行并将其传递给上一个活动。 getCheckedItemPositions()返回“可检查”(true或false)行的数量,而不是所选行的行数。在我看来,该方法的名称具有误导性。我将迭代getCheckedItemPositions()以获取真实的并将所选行的数量传递给上一个活动。我想知道它可能比我的解决方案更好吗?
以下是以前的代码 -
final SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
Team team;
final int checkedItemsCount = checkedItems.size();
int[] ids = new int [checkedItemsCount];
for (int i = 0; i < checkedItemsCount; ++i) {
team = new Team();
team = mListAdapter.getItem(checkedItems.keyAt(i));
list.add(team);
ids[i] = team.getTeamId();
}
Intent i = new Intent();
i.putExtra(INTENT_TEAM_SELECTION_SIZE, list.size());
i.putExtra(INTENT_TEAM_IDS, ids);
setResult(RESULT_OK, i);
finish();
我的更新代码 -
final SparseBooleanArray checkedItems = mListView.getCheckedItemPositions();
Team team;
final int checkableItemsCount = checkedItems.size();
int selectedItemsCount = 0;
//get the count of selected rows
for (int i = 0; i < checkableItemsCount; ++i) {
if (checkedItems.valueAt(i)) {
selectedItemsCount++;
}
}
//Initialize the array of ids by the number of selected rows
int[] ids = new int[selectedItemsCount];
int index = 0;
for (int i = 0; i < checkableItemsCount; ++i) {
if (checkedItems.valueAt(i)) {
team = new Team();
team = mListAdapter.getItem(checkedItems.keyAt(i));
ids[index] = team.getTeamId();
index++;
}
}
Intent i = new Intent();
i.putExtra(INTENT_TEAM_SELECTION_SIZE, selectedItemsCount);
i.putExtra(INTENT_TEAM_IDS, ids);
setResult(RESULT_OK, i);
finish();