2016-12-26 3 views
0

J'essaie de changer la couleur d'arrière-plan lorsque je dessine la toile d'un élément CardView. J'essaie donc d'obtenir la couleur d'arrière-plan sur l'événement onDraw, mais je ne comprends pas.Android ob Couleur d'arrière-plan sur le dessin

Comment obtenir la couleur d'arrière-plan sur l'événement 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); 
    } 
} 

Répondre

0

Conseils: éviter les allocations dans 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); 
    } 
}