Android ListView 使用key-value map 类型结构可能吗?

标签 android listview

我有一个从字符串数组资源填充的 ListView。我试图找出如何使用键值类型的结构,以便键显示在 ListView 中,并且当选择一行时我可以获得值。

我知道我可以为值维护一个单独的数组并使用行的选定索引进行查找,但这很难维护。

此外,我认为我可以制作一个 POJO 并使用我自己的自定义列表适配器使用这些对象构建列表,但如果可能的话,我只想使用一个简单的 xml 文件。

我正在阅读文档以查看是否可以在 xml 中执行此操作,但我还没有找到类似的东西?

谢谢你的时间。

最佳答案

您可能想要使用订购的 map ,例如 TreeMapLinkedHashMap并将其传递给您的适配器。

这将实现您想要实现的目标。

您基本上需要有一个适配器,它利用键值对数据结构(Map)并将其设置在您的 ListView 中,例如:



public class OrderedMapAdapter extends BaseAdapter {

        Map.Entry[]  entries;

        /***
         * Pass the key value pair map using an ordered map data structure
         * @param orderedMap An ordered map, either LinkedHashMap or TreeMap
         */
        public OrderedMapAdapter(LinkedHashMap orderedMap) {
            this.entries = orderedMap.entrySet().toArray(new Map.Entry[0]);
        }

        public int getCount() {
            return entries.length;
        }

        /***
         * This should get you the position you want in Key-value pair format
         * that you could use whenever the row is selected
         */
        public Map.Entry getItem(int position) {
            return entries[position];
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // display your view here
            return null;
        }
    }

关于Android ListView 使用key-value map 类型结构可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7163799/

相关文章:

android - 在 YUV 颜色空间中操纵亮度

android - 从 onClickListener 检索图像(保存在 sqlite 中)

android - 如何从其子 Activity 中获取父 Activity 的值(value)并将它们保留在android中?

android - ListItem 中的 WebView -> 项目不可点击 |安卓

android - 将 SeparatedListAdapter 用于 ListView 在 Android 2.1 上崩溃但适用于 2.2

android - 获取 listView 中的值微调器(android)

android - 以变​​量为名称的动态图像

java - 如何限制 EditText 在 Java 中仅输入浮点值?

android ListView后台处理

android - 无法在 Android 中使用字体