开发者

Getting ListView item ID from its ListAdapter's row ID

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 开发者_如何学Pythonrow 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.


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());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜