2013-07-18 38 views
2

我創建了一個自定義ListView和在java中填充ListViewSimpleAdapter。這裏是我的代碼:android listview簡單適配器,項目重複

setContentView(R.layout.activity_my); 
list = (ListView) findViewById(R.id.lvList); 

itemList = new ArrayList<HashMap<String, String>>(); 
itemMap = new HashMap<String, String>(); 

for (int i = 0; i < songs.length; i++) { 
    itemMap.put("song", songs[i]); 
    itemMap.put("artist", artists[i]); 
    System.out.println(songs[i] + "  " + artists[i]); 
    itemList.add(itemMap); 
} 

SimpleAdapter adapter = new SimpleAdapter(this, itemList, 
      android.R.layout.simple_list_item_2, new String[] {"song", 
        "artist"}, new int[] { android.R.id.text1, 
        android.R.id.text2 }); 
list.setAdapter(adapter); 

現在,我創建了兩個String Arrays歌曲和歌手分別放在一個HashMap然後把HashMap一個叫itemListArrayList。之後,我在參數中設置了默認列表項ID的適配器。

我面臨的問題是,當我運行應用程序時,列表視圖只反覆顯示字符串數組的最後一項和子項。這是供參考的圖片。 My ListView

我想知道爲什麼會發生這種情況。我試圖把itemList.add(itemMap);放在for()的循環之外,但它仍然不起作用。幫助將真正讚賞與一個適當的解釋,因爲我有點新的這一點。謝謝!

+0

您一次又一次向'HashMap'添加相同的密鑰。 –

+0

呃一些細節會有所幫助。 – SynerFlow

回答

3

您可以通過在每次迭代中重新創建itemMap對象來實現此目的。嘗試以下方法。

itemMap = new HashMap<String, String>(); 

for (int i = 0; i < songs.length; i++) { 
    itemMap.put("song", songs[i]); 
    itemMap.put("artist", artists[i]); 
    System.out.println(songs[i] + "  " + artists[i]); 
    itemList.add(itemMap); 
} 

更改爲

for (int i = 0; i < songs.length; i++) { 
    itemMap = new HashMap<String, String>(); 
    itemMap.put("song", songs[i]); 
    itemMap.put("artist", artists[i]); 
    System.out.println(songs[i] + "  " + artists[i]); 
    itemList.add(itemMap); 
} 

釋:

Refer這裏。注意HashMap是一個keyvalue對,這意味着它將存儲一個鍵的一些值。所以HashMap將不允許重複密鑰。您的代碼已經添加了songartist的值。所以你不能再添加這些鍵的值。但itemlist在每次迭代中都添加itemMap。這就是重複相同記錄的列表的原因。爲了避免這個問題,只需重新實例化itemMap對象。

我希望這會幫助你。

+0

好的!有效。你能解釋一下爲什麼這會起作用嗎?謝謝 – SynerFlow

+0

哦,天啊!我可以擁抱你! thanx a loooooot :) – afsane

0

兄弟,你不會相信,但你做錯了。

在每次迭代中創建一個HashMap的新對象。

+0

是的,我做錯了,顯然我在2013年7月找到了解決問題的辦法。兄弟,你不會相信,但是你已經9個月太晚了。 – SynerFlow

+0

我相信你我的朋友..我沒有看到帖子日期..:D:P;) – Prakash