我正在尝试创建一个带有彩色方块的选项组,供用户选择。它在 3.2 设备上运行,如下图所示:
代码类似于:
for (int i = 0; i < COLORS.length; i++) {
CheckBox box = new CheckBox(context);
box.setBackgroundDrawable(getColorOption(context, COLORS[i]));
box.setButtonDrawable(android.R.color.transparent);
然后,在 getColorOption 函数中,我创建了 StateListDrawable:
StateListDrawable slDrawable = new StateListDrawable();
LayerDrawable checkedDrawable = new LayerDrawable(new Drawable[] {
new SelectFrameShapeDrawable(transparentColor, lightRedColor),
new SquareShapeDrawable(color) });
LayerDrawable uncheckedDrawable = new LayerDrawable(new Drawable[] {
new SelectFrameShapeDrawable(transparentColor, transparentColor),
new SquareShapeDrawable(color) });
slDrawable.addState(new int[] { android.R.attr.state_checked },
checkedDrawable);
slDrawable.addState(new int[] { -android.R.attr.state_checked }, uncheckedDrawable);
return slDrawable;
SquareShapeDrawable 类是一个 ShapeDrawable:
public class SquareShapeDrawable extends ShapeDrawable {
private final Paint fillpaint;
public SquareShapeDrawable(int color) {
super(new RectShape());
fillpaint = new Paint(this.getPaint());
fillpaint.setColor(color);
}
@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
shape.draw(canvas, fillpaint);
}
}
SelectFrameShapeDrawable 是:
private class SelectFrameShapeDrawable extends ShapeDrawable {
private final Paint fillpaint, strokepaint;
public SelectFrameShapeDrawable(int fill, int stroke) {
super(new RectShape());
strokepaint = new Paint(this.getPaint());
strokepaint.setStyle(Paint.Style.STROKE);
strokepaint.setStrokeWidth((int) (getResources()
.getDisplayMetrics().density + 0.5f));
strokepaint.setColor(stroke);
int padding = (int) (4 * getResources().getDisplayMetrics().density + 0.5f);
setPadding(padding, padding, padding, padding);
fillpaint = new Paint(strokepaint);
fillpaint.setColor(fill);
}
@Override
protected void onDraw(Shape shape, Canvas canvas, Paint paint) {
if (strokepaint != null)
shape.draw(canvas, strokepaint);
shape.draw(canvas, fillpaint);
}
}
在 4.2 设备上,所有方块都是黑色的,并且在选中时不会改变:
问题似乎是在将可绘制对象添加到 StateListDrawable 时......知道如何解决这个问题吗?