加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:35:38 所属栏目:Java 来源:网络整理
导读:如何在ListView中找到特定项目的位置? (由SimpleCursorAdapter填充). 我问的原因:listview设置为singleChoice模式.当用户关闭并重新打开应用程序时,我希望用户的选择被记住. 到目前为止,我完成的方式是当用户点击一个项目时,所选项目的ID被保存到首选项.我
如何在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 to next() 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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读