gpt4 book ai didi

android - 具有偶数行背景颜色的自定义 SimpleCursorAdapter

转载 作者:行者123 更新时间:2023-11-29 14:53:16 27 4
gpt4 key购买 nike

我想实现一个自定义的 SimpleCursorAdapter,它只在偶数行上显示背景颜色(在我的例子中是蓝色)。我的实现如下:

public class ColoredCursorAdapter extends SimpleCursorAdapter {
String backgroundColor;

public ColoredCursorAdapter(
Context context,
int layout,
String backgroundColor,
Cursor c,
String[] from,
int[] to,
int flags) {
super(
context,
layout,
c,
from,
to,
flags);
this.backgroundColor = backgroundColor;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
if(cursor.getPosition() % 2 == 0) {
view.setBackgroundColor(
Color.parseColor(backgroundColor));
}
}
}

一开始它工作正常,但是当我反复上下滚动列表时,所有行都变成蓝色。

提前致谢。

最佳答案

当您四处滚动时,适配器会回收(重复使用)项目 View 。这意味着当您来回滚动列表时,您不能保证相同的项目 View 将用于给定的光标位置。在您的情况下,如果当前位置是偶数,您只能设置项目 View 的背景颜色,但是您当前处理的特定 View 可能以前曾在奇数位置使用过。因此,随着时间的推移,您所有的项目 View 都会获得相同的背景颜色。

虽然解决方案很简单,但为奇数和偶数光标位置设置背景颜色。像这样的东西:

@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
if(cursor.getPosition() % 2 == 0) {
view.setBackgroundColor(
Color.parseColor(backgroundColor));
}else{
view.setBackgroundColor(
Color.parseColor(someOtherBackgroundColor));
}
}

关于android - 具有偶数行背景颜色的自定义 SimpleCursorAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310836/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com