开发者

Android ListView using a key-value map type structure possible?

开发者 https://www.devze.com 2023-03-29 22:26 出处:网络
I have a ListView which is populated from a string-array resource. I\'m trying to figure out how I can use a key-value type of structure, so that the key is displayed in the ListView, and when a row i

I have a ListView which is populated from a string-array resource. I'm trying to figure out how I can use a key-value type of structure, so that the key is displayed in the ListView, and when a row is selec开发者_JAVA技巧ted I can get the value.

I know I could maintain a separate array for the values and do a lookup using the selected index of the row but this is hard to maintain.

Also I think I could make a POJO and build the list with those objects with my own custom list adaptor, but I want to just use a simple xml file if possible.

I'm reading the documentation to see if I can do this in xml but I've not found anything like this yet?

Thanks for you time.


You might want to use the Map that is ordered such as TreeMap or LinkedHashMap and pass it to your adapter.

This would enable what you are trying to achieve.

You basically need to have an adapter that utilize the Key-Value pair data structure (Map) and set it in your list view, something like:



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


I believe your second suggestion using a custom list adapter is going to be the easiest solution for what you want to do.

The SimpleAdapter drives the XML file approach you mentioned and is quite particular on the format of data it receives. If you can restructure the format of your input data to match, the SimpleAdapter will work fine.

Otherwise use the ArrayAdapter and a POJO, and build the list required for your implementation.


I have just created a bunch of POJOs and used a custom list adapter to display the relevant data from the Object in the List Row.

0

精彩评论

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