找一个ListView中的项的位置? [英] Get position of an item within a ListView?
问题描述
一个人怎么会找到一个特定项目的ListView控件中的位置? (由SimpleCursorAdapter填充)。
How would one find the position of a specific item within a ListView? (Populated by SimpleCursorAdapter).
我之所以问:ListView控件设置为singleChoice模式。当用户关闭并重新打开应用程序,我想用户的选择被人记住。
The reason I ask: The listview is set to singleChoice mode. When the user closes and reopens the app, I'd like the user's selection to be remembered.
就是我已经做到了,到目前为止是当用户点击一个项目,所选项目的ID被保存到preferences。我需要学习的是如何重新选择的项目在活动的onCreate方法,一旦它被重新填充。
The way I've done it so far is when the user clicks on an item, the ID of the chosen item is saved to preferences. What I need to learn is how to reselect the item in the activity's onCreate method once it's been repopulated.
我的code保存所选项目的ID:
My code for saving the selected item's ID:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = (Cursor) l.getItemAtPosition(position);
selectedItem = c.getLong(c.getColumnIndex("_id"));
}
(我试过在Google上搜寻,但只能似乎找到如何获得的位置选择的项目)
谢谢!
推荐答案
您应该尝试
//SimpleCursorAdapter adapter;
final int position = adapter.getCursor().getPosition();
API文档:
public abstract int getPosition ()
自:API级别1
返回的当前位置
在游标的行集。该值是
从零开始的。当行集是第一
返回的光标将在当前位置
-1,这是第一行之前。返回的最后一行之后的另一
来电下一个()
将离开光标
过去的最后一个条目,在一个位置
计数()
。
Returns the current position of the cursor in the row set. The value is zero-based. When the row set is first returned the cursor will be at positon -1, which is before the first row. After the last row is returned another call to
next()
will leave the cursor past the last entry, at a position ofcount()
.
返回 当前光标位置。
更新
要获得基于适配器使用该ID的项目的位置:
To get an item's position based on the id used by the adapter:
private int getItemPositionByAdapterId(final long id)
{
for (int i = 0; i < adapter.getCount(); i++)
{
if (adapter.getItemId(i) == id)
return i;
}
return -1;
}
要获得基于基本对象的属性项目的位置(成员值)
To get an item's position based on the underlying object's properties (member values)
//here i use `id`, which i assume is a member of a `MyObject` class,
//and this class is used to represent the data of the items inside your list:
private int getItemPositionByObjectId(final long id)
{
for (int i = 0; i < adapter.getCount(); i++)
{
if (((MyObject)adapter.getItem(i)).getId() == id)
return i;
}
return -1;
}
这篇关于找一个ListView中的项的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!