如何在ListView中找到特定项目的位置? (由SimpleCursorAdapter填充).
我问的原因:listview设置为singleChoice模式.当用户关闭并重新打开应用程序时,我希望用户的选择被记住.
到目前为止,我完成的方式是当用户点击一个项目时,所选项目的ID被保存到首选项.我需要学习的是如何重新填充活动的onCreate方法中的项目.
我的代码保存所选项目的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")); }
(我已经尝试过谷歌搜索,但只是看起来如何找到所选项目的位置)
谢谢!
解决方法
你应该试试
//SimpleCursorAdapter adapter; final int position = adapter.getCursor().getPosition();
API文件:
public abstract int getPosition ()
自:API 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 tonext()
will leave the cursor
past the last entry,at a position of
count()
.
返回
当前光标位置.
更新
根据适配器使用的ID获取项目的位置:
private int getItemPositionByAdapterId(final long id) { for (int i = 0; i < adapter.getCount(); i++) { if (adapter.getItemId(i) == id) return i; } return -1; }
//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; }