What adapter shall I use to use HashMap in a ListView

后端 未结 6 1592
轮回少年
轮回少年 2020-11-27 04:42

I want to use HashMap for a list of items of Adapter for a ListView. I was going to use ArrayAdapter<> but I can\'t

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 05:28

    Thanks for the answer longhairedsi

    This comes with the following caveat, the order of the items is not guaranteed to be the same order you added them. Writing this example has made me realize; Don't use HashMap in an adapter :)

    To get around this problem, use a LinkedHashMap instead.

    public class HashMapAdapter extends BaseAdapter {
        private LinkedHashMap mData = new LinkedHashMap();
        private String[] mKeys;
        public HashMapAdapter(LinkedHashMap data){
            mData  = data;
            mKeys = mData.keySet().toArray(new String[data.size()]);
        }
    
        @Override
        public int getCount() {
            return mData.size();
        }
    
        @Override
        public Object getItem(int position) {
            return mData.get(mKeys[position]);
        }
    
        @Override
        public long getItemId(int arg0) {
            return arg0;
        }
    
        @Override
        public View getView(int pos, View convertView, ViewGroup parent) {
            String key = mKeys[pos];
            String Value = getItem(pos).toString();
    
            //do your view stuff here
    
            return convertView;
        }
    }
    

提交回复
热议问题