【发布时间】:2015-08-10 11:11:39
【问题描述】:
我想为我的自定义 ListView 类设置交替颜色。
代码如下:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ListView;
public class CustomListView extends ListView {
private Paint mPaint = new Paint();
private Paint mPaintBackground = new Paint();
public CustomListView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint.setColor(Color.parseColor("#1A000000"));
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
final int currentHeight = getMeasuredHeight();
final View lastChild = getChildAt(getChildCount() - 1);
if (lastChild == null)
return;
for (int i = 0; i < getChildCount(); i++) {
if (getChildCount() % 2 == 0) {
mPaintBackground.setColor(Color.WHITE);
} else {
mPaintBackground.setColor(Color.RED);
}
}
final int lastChildBottom = lastChild.getBottom();
final int lastChildHeight = lastChild.getMeasuredHeight();
final int nrOfLines = (currentHeight - lastChildBottom) / lastChildHeight;
Rect r = new Rect(0, lastChildBottom, getMeasuredWidth(), getMeasuredHeight());
canvas.drawRect(r, mPaintBackground);
canvas.drawLine(0, lastChildBottom, getMeasuredWidth(), lastChildBottom, mPaint);
for (int i = 0; i < nrOfLines; i++) {
canvas.drawLine(0, lastChildBottom + (i + 1) * lastChildHeight, getMeasuredWidth(), lastChildBottom + (i + 1) * lastChildHeight, mPaint);
}
return;
}
}
为了获得ListView 的交替背景颜色,我使用了以下代码:
for (int i = 0; i < getChildCount(); i++) {
if (getChildCount() % 2 == 0) {
mPaintBackground.setColor(Color.WHITE);
} else {
mPaintBackground.setColor(Color.RED);
}
}
适配器内部:
if (position % 2 == 0) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
但它总是显示一种颜色,红色或白色与我尝试的一切。我没有得到白色-红色-白色-红色交替的颜色。
【问题讨论】:
-
你使用了错误的方法来达到你的结果。 dispatchDraw 方法只被调用一次。对于每个项目都调用的这种行为,您应该使用 getView 方法。 @faizan 提出了正确的解决方案
-
哦。真的吗 ?那会怎么样呢?
-
查看完整评论。
-
@SAIR 你检查过我编辑过的问题吗?我还发布了我的适配器代码。!
-
适配器代码只有在有有数据时才会起作用。如果你想在没有数据的情况下为整个 ListView 交替颜色,则必须在 dispatchDraw 中完成。我现在正在尝试编辑我的答案。