问题
I created a custom ListView
and in java filled that ListView
with a SimpleAdapter
. Here's my code:
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);
Now I created two String Arrays
Song and Artist respectively and put them in a HashMap
and then put the HashMap
in a ArrayList
called itemList
. After that i set up the adapter with the default list item id's in the parameter.
The problem I am facing is that when i run the application, the list view shows only the last item and subItem of the String Arrays repeatedly. Here's the image for reference. My ListView
I'd like to know why this is happening. I tried putting the itemList.add(itemMap);
outside the for()
loop but it still didn't work. Help would really be appreciated with a proper explanation, cause i'm kinda new to this. Thank You!
回答1:
You can achieve this by recreating your itemMap
object at every iteration. Try the following way.
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);
}
Change this to
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);
}
Explaination:
Refer here. Note HashMap
is a key
value
pair which means it will store some value for a key. So HashMap
will not allow duplicate key. From your code already youe have added the value for song
and artist
. So you can not add the value for these keys again. But the itemlist
add the itemMap
at every iteration. That is why the list repeating the same record. To avoid this problem simply re instantiate the itemMap
object.
I hope this will help you.
回答2:
bro, you won't believe but you are doing wrong.
make a new object of HashMap on each iteration.
来源:https://stackoverflow.com/questions/17714580/android-listview-simple-adapter-item-repeating