我想創建一個帶彩色正方形的選項組,供用戶選擇一個。它正在開發一種3.2設備上,並且在這張圖片看起來像: StateListDrawable與編程創建的LayerDrawable不能在Android 4.0+上工作
的代碼是一樣的東西:
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時.. 任何想法如何解決這個問題?
爲什麼它使用StateListDreawable工作? – jonney 2014-10-24 22:15:29