Android在绘制时获得背景颜色

时间:2016-12-26 17:13:31

标签: android canvas background draw

当我绘制CardView元素的画布时,我正在尝试更改背景颜色。所以我试图在onDraw事件上获得背景颜色,但我没有得到。

我如何获得CardView onDaw事件的背景颜色?

public class MyCardView extends CardView {
    public MyCardView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int bgColor = ???some method???;
        if(bgColor == 0) {
            setBackgroundColor(Color.RED);
        }
        super.onDraw(canvas);
    }
}

1 个答案:

答案 0 :(得分:0)

提示:避免onDraw()

中的分配
public class MyCardView extends CardView {
    private Drawable background;
    private int color = Color.RED;

    public MyCardView(Context context) {
        super(context);
        background = ((View) this.getParent()).getBackground();
        if (background instanceof ColorDrawable) {
            color = ((ColorDrawable) background).getColor();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        setBackgroundColor(color);
        super.onDraw(canvas);
    }
}