简体   繁体   English

ListView项目更改背景颜色

[英]ListView items change background color

I'm having a weird behaviour in my application... A have a ListView, where odd items have #ffffff background and even items have #f2f7f7 , and looks like this: 我的应用程序中出现奇怪的行为... A具有ListView,其中奇数项具有#ffffff背景,偶数项具有#f2f7f7 ,如下所示:

活动开始或触摸列表(不发布)

However, as soon as I start scrolling the list, the even items slightly change color, becoming #f7f7f7 , like this: 但是,一旦我开始滚动列表,偶数项就会稍微改变颜色,变成#f7f7f7 ,如下所示:

滚动时和滚动释放后

Any ideas? 有任何想法吗? If you need more info, please ask. 如果您需要更多信息,请询问。 I'm baffeld with this behaviour. 我很喜欢这种行为。

Additional info: 附加信息:

I'm setting each item's background color in getView() method, like this: 我在getView()方法中设置每个项目的背景色,如下所示:

protected final int[] colors = new int[] { R.drawable.states_list_odd, R.drawable.states_list_even };
...
// Alternates list items' background
int colorPos = position % colors.length;
convertView.setBackgroundResource(colors[colorPos]);

Simple stuff, actually. 简单的东西,实际上。 android:scrollingCache="false" solved this issue. android:scrollingCache="false"解决了此问题。

The Views used for the items are being reused when you scroll the list (there's no need to create the new ones). 滚动列表时,将重新使用用于项目的视图(无需创建新视图)。 So, when you scroll down the list, the item at position 0 may be rendered at position 10. It will be the same View object, and before showing getView will be called with convertView parameter set to this particular View - so you can fill it with data (and specify your styles). 因此,当您向下滚动列表时,位置0处的项目可能会在位置10处呈现。它将是相同的View对象,并且在显示getView之前,将convertView参数设置为此特定View进行调用-这样就可以填充它与数据(并指定您的样式)。 It's just an optimization. 这只是一个优化。

So, you need to specify the background color for the item each time getView is called for it in your list adapter. 因此,您需要在列表适配器中每次为其调用getView时指定该项目的背景色。

programmaticly try this. 以编程方式尝试此操作。 yourListView.setScrollingCacheEnabled(false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM