I'm trying to get a ListView to toggle the background color of its elements when they are selected (this is for selecting songs to add to a playlist). I've been mostly successful, but for some reason whenever the ListView is longer than the screen, selecting either the first or last item also toggles the background of the other. I keep track of whether an item is selected or not in an array of booleans called selectedStatus, and there's not a problem there, so it's purely a UI problem.
Here's the relevant section of the code:
boolean selectedStatus{} = new boolean[songsList.size()];
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lv = getListView();
// listening for song selection
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int viewPosition = position - lv.getFirstVisiblePosition();
if(selectedStatus[position]){
selectedStatus[position] = false;
View currentEntry = lv.getChildAt(viewPosition);
currentEntry.setBackgroundResource(R.color.footercolor);
}
else{
selectedStatus[position] = true;
View currentEntry = lv.getChildAt(viewPosition);
currentEntry.setBackgroundResource(R.color.selected);
}
}
});
}
There must be some implementation detail about ListViews that I'm missing, but I can't figure out why this would be happening.
EDIT: I've realized with more testing that it actually links all list elements with positions which are equal mod 12, I just wasn't looking at a long enough list. This seems much less weird, it's just reusing elements, and I'll have to look into this ViewHolder idea.
Since a few people asked, this is all the code I have for making an adapter and populating the list:
// Adding items to ListView
ListAdapter adapter = new ArrayAdapter<String>(getActivity(),
R.layout.playlist_builder_item, songnamesList);
setListAdapter(adapter);