我有一个通过 ArrayAdapter 填充的 ListView。在适配器中,我根据条件设置视图背景颜色。它有效,但是在滚动时其余行采用这种颜色。这是一些代码:
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 设置为透明来覆盖它。
只需添加,
android:cacheColorHint="#00000000"
在你的 xml 文件中。
欲了解更多详情,您可以浏览列表视图背景 http://developer.android.com/resources/articles/listview-backgrounds.html文章。
以下是摘录:
要解决此问题,您所要做的就是禁用缓存颜色提示优化(如果您使用非纯色背景),或者将提示设置为适当的纯色值。您可以从代码中执行此操作(请参阅 setCacheColorHint(int)),或者最好使用 android:cacheColorHint 属性从 XML 中执行此操作。要禁用优化,只需使用透明颜色#00000000。以下屏幕截图显示了在 XML 布局文件中设置 android:cacheColorHint="#00000000" 的列表
编辑:作为convertView传递的视图本质上是一个视图,它是列表视图的一部分,但不再可见(由于滚动)。所以它实际上是您创建的视图,并且可能是您设置了自定义背景的视图。要解决此问题,只需确保在不满足条件时重置背景即可。像这样的东西:
if(condition_satisfied) {
//set custom background for view
}
else {
//set default background for view
convertView.setBackgroundResource(android.R.drawable.list_selector_background);
}
基本上,如果您的条件不满足,您将不得不undo当您的条件满足时,您正在执行任何自定义操作,因为您可能收到了旧的自定义视图convertView
。
那应该可以解决你的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)