我的 Android 应用程序中有一个两种颜色ListView
的 s(一种颜色用于奇数元素,一种用于偶数元素)。它在 Froyo 上运行良好。但是在 Jelly Bean 模拟器上,滚动过程中会出现一些伪影。某些元素的背景变为黑色。是的,我知道带有透明缓存颜色提示的解决方案!但只有当我以这种方式设置背景时它才有效:
在bindView()
适配器方法中:
// ...
view.setBackgroundResource(
cursor.getPosition() % 2 == 0 ? R.color.list_item_bg1: R.color.list_item_bg2);
但是这种方法不适合我,因为我想突出显示元素,然后用户点击它。所以我StateListDrawable
为此目的使用:
mOddColorDrawable = new ColorDrawable(
context.getResources().getColor(R.color.list_item_bg2));
mEvenColorDrawable = new ColorDrawable(
context.getResources().getColor(R.color.list_item_bg1));
mSelector = new ColorDrawable(
context.getResources().getColor(R.color.list_item_selector));
public void bindView(View view, Context context, Cursor cursor) {
// ...
setBackground(cursor.getPosition % 2 != 0, view);
}
public void setBackground(boolean isOdd, View listItem) {
StateListDrawable dr = new StateListDrawable();
Drawable drColor = isOdd ? mOddColorDrawable : mEvenColorDrawable;
dr.addState(new int[] { android.R.attr.state_pressed }, mSelectorDrawable);
dr.addState(new int[] { -android.R.attr.state_pressed }, drColor);
listItem.setBackgroundDrawable(bg);
}
因此,即使我为ListView
. 我花了几天时间调查这个问题,但无法克服它。所以,你是我最后的希望,StackOverflow!
概括:
- 我想让 ListView 有两种不同的元素颜色。
- 我想要具有自定义颜色的项目选择器。
- 如果我使用 StateListDrawable,setCacheColorHint(transparent) 没有帮助。
- 在 Froyo 上一切正常,但在 Jelly Bean 上却不行。