我有一个ListView,它通过ArrayAdapter填充.在适配器中,我根据条件设置视图背景颜色.它可以工作,但滚动剩余的行时采用这种颜色.这是一些代码: class DateAdapter extends ArrayAdapterDateVO { private
class DateAdapter extends ArrayAdapter<DateVO> { private ArrayList<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; } }这是ListView的默认行为.可以通过将cacheColorHint设置为transparent来覆盖它.
只需添加,
android:cacheColorHint="#00000000"
在您的xml文件中.
有关详细信息,请阅读ListView Backgrounds文章.
这是一段摘录:
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
编辑:作为convertView传递的视图本质上是一个视图,它是列表视图的一部分,但不再可见(由于滚动).因此它实际上是您创建的视图,可能是您已设置自定义背景的视图.要解决此问题,请确保在不满足条件时重置背景.像这样的东西:
if(condition_satisfied) { //set custom background for view } else { //set default background for view convertView.setBackgroundResource(android.R.drawable.list_selector_background); }
基本上,如果您的条件不满意,您将不得不撤消满足条件时正在执行的任何自定义操作,因为您可能已收到旧的自定义视图作为convertView.那应该可以解决你的问题.