【发布时间】:2015-02-16 13:33:16
【问题描述】:
我是 Android 和 Java 新手。我想知道是否有办法通过值来查找 ListView 项的位置。
例如:
如果我的 ListView 中有一个项目显示字符串“Product 1108”,我将如何获得“Product 1108”的位置?
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getKey().equals(currentList + entry.getValue())) {
checkListStrings.add((String) entry.getValue());
}
if (entry.getKey().equals(currentList + entry.getValue() + "Checked")) {
//set Item to checked / unchecked
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_checked,
checkListStrings);
lvCheckList.setAdapter(checkListArrayAdapter);
}
此代码获取存储在 SharedPreferences 中的项目并将它们显示在 ListView 中。不要问我为什么它有效,它就是有效。
现在看到这一行:
if (entry.getKey().equals(currentList + entry.getValue() + "Checked")) {
//set Item to checked / unchecked
}
我想要在这里发生的是将列表项设置为选中或未选中,但我认为这不可能,因为尚未填充列表视图。因此,在 ArrayAdapter 中,我需要对列表视图的项目进行排序,找到具有我要查找的任何值的项目,并获取该项目的位置,以便我可以使用以下代码:
lvCheckList.setItemChecked(position, value);
希望这是有道理的。
【问题讨论】:
-
你是如何获得价值的?
-
值是从 SharedPreferences 加载的。
-
为什么需要它? (我不知道你可以在什么情况下知道显示值但你没有同时拥有位置)