开发者

Android - ListView and tag

I have been using ArrayListAdapter on ListView objects. I am wondering if there is a simple way to 开发者_StackOverflowstore some extra data for each listview item as a tag object.


Usually you use a string array or list as data for an array list and the adapter method getItem(position) will return the corresponding string.

But you can use any object array or list as input and so pass any data as list item. For example:

class MyListItem {

    private int mId;
    private Object mData;
    private String mListItemName;

    public MyListItem(int id, Object data, String name) {
        mId = id;
        mData = data;
        mListItemName = name;
    }

    @Override
    public String toString() {
        return mListItemName;
    }
}

You can pass an array of MyListItem to the array adapter and it will use toString() to get the names for the items. You can get the item data with (MyListItem) adapter.getItem(position).


A note about list adapters that support filtering. It is easy to logically relate the position value provided by onItemClick() with the index of an associated array. However, doing so causes problems when the list is filtered.

Case in point: A filtered SimpleAdapter. Unfiltered, onItemClick() provides the position of the item in a ListView as well as the position of item in an array associated with a ListView. After filtering, onItemClick provides the position of the item in the displayed list, but it no longer matches the index of the item in the associated array. getItemAtPosition(), however, uses the position value to retrieve the correct item from the associated array. getItemAtPosition() provides the correct record in a CursorAdapter as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜