获取ListView项ID从ListAdapter的行ID [英] Getting ListView item ID from its ListAdapter's row ID

查看:544
本文介绍了获取ListView项ID从ListAdapter的行ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个单项选择题(例如,单选按钮),这些从数据库中查询到的产品清单。与当前所选行工作,我需要使用 getCheckedItemPosition的ListView() setItemChecked()方法。

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.

我有一个的ListView ,有一个设置就可以了 SimpleCursorAdapter 。当我检索当前选定的项目,我有它的行ID 从数据库中,我需要使用找到合适的项目,并手动将其设置为可通过上述方法选择。换句话说,我需要行ID的状态映射到一定单调行ID(因为 setItemChecked()方法接受一个位置ID,而不是数据库行ID ,并在我的数据库,我可以删除项目)。

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).

那么,有没有办法可以从表行ID的位置ID?我宁愿不诉诸做的,如果可能的搜索。

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.

感谢。

推荐答案

我最终只是创造,通过所有的项目搜索(这被认为是按顺序)一个简单的方法:

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

编辑:做这样的事情,请使用此code:

Use this code by doing something like this:

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

这篇关于获取ListView项ID从ListAdapter的行ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆