Reputation: 60184
I need to have even rows as white and odd rows sd grey in my ListView
(using ArrayAdapter
to populate it). I can't use different layouts
with different background
color because if I do the selection doesn't work. What I do is just use this piece of code in my getView()
to check if row is odd or even and apply background depending on condition:
if (position % 2 == 0) {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.dark_item_background));}
But this doesn't work as expected because the only first visible rows are of correct background color. After scrolling to the bottom (I assume because of recycling mechanism) I have very weird behavior and don't understand why. Here is what I have for the first items (correct case):
Here is what I have after scrolling:
Upvotes: 3
Views: 347
Reputation: 22527
In getView()
objects are reused for better performance.Thats why you get this weird behavior. To solve your problem just add if - else
if (position % 2 == 0) {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.dark_item_background));
} else {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.light_item_background));
}
Upvotes: 4
Reputation: 23638
I think you need to set the background of the listview rows as below:
if (position % 2 == 0) {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.dark_item_background));
}
else
{ convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.light_item_background));
}
Upvotes: 1
Reputation: 3948
You need to set the ELSE cause as well otherwise all the backgrounds will become black because of the reusing mechanism.
if (position % 2 == 0) {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.dark_item_background));
} else {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.light_item_background));
}
Upvotes: 1
Reputation: 3915
I think you need to set default color for any reused convert view first, because convert view already can have dark background. So it would be something like this:
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.light_item_background));
if (position % 2 == 0) {
convertView.setBackgroundDrawable(getResources().getDrawable(R.drawable.dark_item_background));
}
Upvotes: 1