2016-12-26 157 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); 
    } 
} 
避免分配