java – 获取ListView中的项目的位置?

前端之家收集整理的这篇文章主要介绍了java – 获取ListView中的项目的位置?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在ListView中找到特定项目的位置? (由SimpleCursorAdapter填充).

我问的原因:listview设置为singleChoice模式.当用户关闭并重新打开应用程序时,我希望用户的选择被记住.

到目前为止,我完成的方式是当用户点击一个项目时,所选项目的ID被保存到首选项.我需要学习的是如何重新填充活动的onCreate方法中的项目.

我的代码保存所选项目的ID:

@H_403_8@@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")); }

(我已经尝试过谷歌搜索,但只是看起来如何找到所选项目的位置)

谢谢!

解决方法

你应该试试 @H_403_8@//SimpleCursorAdapter adapter; final int position = adapter.getCursor().getPosition();

API文件

@H_403_8@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 to next() will leave the cursor
past the last entry,at a position of
count().

返回
当前光标位置.

更新

根据适配器使用的ID获取项目的位置:

@H_403_8@private int getItemPositionByAdapterId(final long id) { for (int i = 0; i < adapter.getCount(); i++) { if (adapter.getItemId(i) == id) return i; } return -1; }

要根据基础对象的属性(成员值)获取项目的位置,

@H_403_8@//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; }
原文链接:https://www.f2er.com/java/122056.html

猜你在找的Java相关文章