2016-12-26 128 views
0

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

如何获取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); 
    } 
} 

回答

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); 
    } 
} 
避免分配