Get position of an item within a ListView?

后端 未结 3 1856
無奈伤痛
無奈伤痛 2021-02-08 20:05

How would one find the position of a specific item within a ListView? (Populated by SimpleCursorAdapter).

The reason I ask: The listview is set to singleChoice mode. Whe

3条回答
  •  后悔当初
    2021-02-08 20:27

    You should try

    //SimpleCursorAdapter adapter;
    final int position = adapter.getCursor().getPosition();
    

    API Docs:

    public abstract int getPosition () 
    

    Since: API Level 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().

    Returns the current cursor position.

    Update

    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;
    }
    

提交回复
热议问题