Android + ListView background sets background while scrolling?
I have a ListView that's populated via an ArrayAdapter. Within the adapter, i set the view background color dependent on a conditional. It works, but while scrolling the remaining rows adopt this color. Here's some code:
class DateAdapter extends ArrayAdapter<DateVO> {
private ArrayList&l开发者_如何学JAVAt;DateVO> items;
public ViewGroup listViewItem;
//constructor
public DateAdapter(Context context, int textViewResourceId, ArrayList<DateVO> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
if (view == null) {
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.row, null);
}
final DateVO dateItem = items.get(position);
if (dateItem != null) {
//is this my issue here? does position change while scrolling?
if(items.get(position).getField().equals("home")){
view.setBackgroundResource(R.drawable.list_bg_home);
}
...
}
}catch (Exception e) {
Log.i(ArrayAdapter.class.toString(), e.getMessage());
}
return view;
}
}
That is the default behavior of a ListView. It can be overridden by setting the cacheColorHint to transparent. Just add,
android:cacheColorHint="#00000000"
in your xml file.
For more details you can go through the ListView Backgrounds article. Here is an excerpt:
To fix this issue, all you have to do is either disable the cache color hint optimization, if you use a non-solid color background, or set the hint to the appropriate solid color value. You can do this from code (see setCacheColorHint(int)) or preferably from XML, by using the android:cacheColorHint attribute. To disable the optimization, simply use the transparent color #00000000. The following screenshot shows a list with android:cacheColorHint="#00000000" set in the XML layout file
EDIT : The view passed as convertView is essentially a view which is a part of the list view, but isn't visible anymore (due to scrolling). So it is actually a view you had created, and might be a view for which you had set the custom background. To solve this just make sure that you reset the background if the condition is not satisfied. Something like this :
if(condition_satisfied) {
//set custom background for view
}
else {
//set default background for view
convertView.setBackgroundResource(android.R.drawable.list_selector_background);
}
Essentially if your condition is not satisfied you will have to undo whatever customisations you are doing when your condition is satisfied, because you might have received an old customised view as convertView
.
That should solve your problem.
精彩评论