2012-04-04 82 views
0

如果我有一個包含以下一個HashMap:創建自定義hashmapadapter

Hashmap contains (String, String) 

我如何實例化一個自定義適配器?自定義適配器應該擴展baseadapter。 我需要將鍵和值組合起來,使其看起來像「KEY + VALUE」,「KEY + VALUE」...並將其分配給數組VALUES。當我檢驗我的自定義adpter時,稍後會使用數組VALUES。

實例化應該是這個樣子:

MyCustomAdapter adapter = new MyCustomAdapter(this, android.R.layout.simple_list_item_1, VALUES); 
setListAdapter(adapter) 

我在這裏失去了代碼,將是一個很大的幫助。

THANKS 格雷厄姆

下面的列表是使用作爲其DataSource被叫項字符串數組。

public ArrayList<String> myList = new ArrayList<String>(Arrays.asList(items)); 

但是項目是一個字符串數組,我想停止使用,而開始使用級聯鍵+值對從我的HashMap

所以不是用戶所呈現的項目,他將成爲一個列表提供了從HashMap中獲取的鍵+值對列表hm

+0

我真的如果你想展現給用戶的鍵+值列表不明白你正在嘗試做的...你只需要在我的答案中使用代碼。嘗試看到這[鏈接](http://stackoverflow.com/questions/5234576/what-adapter-shall-i-use-to-use-hashmap-in-a-listview)。 – Ant4res 2012-04-04 12:40:16

回答

1

我不認爲您需要使用自定義適配器。你的佈局很簡單,你只需要一個textView,所以你可以使用ArrayAdapter。 因爲你比如你可以這樣做:

HashMap<Integer,String>hm=new HashMap<Integer,String>(); 
Vector<String>elements=new Vector<String>(); 
for(int i=0; i<=10;i){  
     hm.put(i,("num"+i)); 
    } 
    for (Entry<Integer, String> e : hm.entrySet()) { 
     String newString=e.toString(); 
     elements.add(newString); 
    } 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elements); 
    list.setAdapter(adapter); 
+0

嗨,它現在看起來更好,但在我的列表中,我得到0 = num1 ....我想用下面的hashmap hm.put(「one」,「Apple」)的值填充它。 hm.put(「two」,「Mango」); hm.put(「三」,「葡萄」); (int i = 0; i <= 10; i ++){hm.put(1,「Apple」);這些值和關鍵字應該包含在元素中,謝謝 – user803271 2012-04-04 10:08:02

+0

FIGURED IT OUT for hm.put(2,「Mango」); hm.put(3,「葡萄」); hm.put(4,「Orange」); hm.put(5,「Peach」); }(Entry e:hm.entrySet()){String newString = e.toString(); elements.add(newString); } – user803271 2012-04-04 10:10:21

+0

你希望他們如何出現在列表中?只有蘋果,芒果和葡萄?爲此,只需使用'e.getValue()。toString()'來更改'e.toString()'。 – Ant4res 2012-04-04 10:11:13