Ich möchte eine alternierende Farbe für meine benutzerdefinierte ListView
Klasse festlegen.Alternative Hintergrundfarbe für die ListView-Klasse auch ohne Daten
Der Code ist unten angegeben:
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;
}
}
Um eine wechselnde Hintergrundfarbe für ListView
zu bekommen, habe ich diesen Code verwendet:
for (int i = 0; i < getChildCount(); i++) {
if (getChildCount() % 2 == 0) {
mPaintBackground.setColor(Color.WHITE);
} else {
mPaintBackground.setColor(Color.RED);
}
}
Innerhalb des Adapters:
if (position % 2 == 0) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.WHITE);
}
Aber es zeigt immer eine Farbe, rot oder weiß mit allem, was ich versuche. Ich bekomme keine wechselnden Farben weiß-rot-weiß-rot.
Sie verwenden eine falsche Methode, um Ihr Ergebnis zu erzielen. Die Methode dispatchDraw wird nur einmal aufgerufen. Sie sollten die getView-Methode für ein solches Verhalten verwenden, das für jedes Element aufgerufen wird. @faizan hat die richtige Lösung vorgeschlagen – SAIR
Oh. Ja wirklich ? So wie es wäre? – Piyush
sehen Sie den kompletten Kommentar. – SAIR