Getting ListView item ID from its ListAdapter's row ID

梦想与她 提交于 2019-12-23 03:36:26

问题


I am trying to create a single-choice (e.g., radio button) list of items that are queried from a database. To work with the currently selected row, I need to use the getCheckedItemPosition() and setItemChecked() methods of ListView.

I have a ListView that has a SimpleCursorAdapter set on it. When I retrieve the currently selected item, I have its row ID from the database, which I need to use to find the appropriate item and manually set it to be selected via the aforementioned methods. In other words, I need to map the status of a row ID to a necessarily monotonic row ID (because the setItemChecked() method accepts a position ID, not a database row ID, and in my database I can remove items).

So is there a way I can get a position id from a table row id? I'd rather not resort to doing a search if possible.

Thanks.


回答1:


I ended up just creating a simple method that searches through all the items (which are assumed to be in order):

/**
 * Since Android apparently provides no way to do this, do a simple binary
 * search for the item position based on its row id.
 * @param adapter    The adapter to use
 * @param row    The rowId to search for
 * @param left
 * @param right
 * @return    Position, or -1 if not found
 */
public int getPositionFromRowId(ListAdapter adapter, long row, int left, int right) {
    if (left > right)
        return -1;
    int middle = (left + right) / 2;
    if (adapter.getItemId(middle) == row)
        return middle;
    if (adapter.getItemId(middle) > row)
        return getPositionFromRowId(adapter, row, left, middle - 1);
    else
        return getPositionFromRowId(adapter, row, middle + 1, right);
}

Edit: Use this code by doing something like this:

getPositionFromRowId(myListAdapter, row, 0, myListAdapter.getCount());


来源:https://stackoverflow.com/questions/6645854/getting-listview-item-id-from-its-listadapters-row-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!