Get position of an item within a ListView?

后端 未结 3 1858
無奈伤痛
無奈伤痛 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:17

    When you say, "...reselecting the item in the activity's onCreate method...", do you mean that when the user returns to the ListView activity, whatever item was previously chosen, is now currently at the top of the screen (assuming enough items appear in the list below it)?

    If so, then from onListItemClick, you should also make an effort to save the value of position, since it tells you the position in the list of the selected item. This would allow you to not need to reverse-lookup the position from the _id.

    Or is that for some reason not an option for your purposes? Do you really need to instead figure out the position from the _id?

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-02-08 20:42

    I do this straightforward in my own app:

    long lastItem = prefs.getLong(getPreferenceName(), -1);
    if (lastItem >= 0) {
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            if (lastItem == cursor.getLong(0)) {
                spinner.setSelection(cursor.getPosition());
                break;
            }
            cursor.moveToNext();
        }
    }
    

    Spinner is populated with the cursor's contents, so I just look through them and compare with the selected item id. In your case that would be a ListView.

    0 讨论(0)
提交回复
热议问题