2013-08-28 2 views
2

J'essaie d'appliquer un arrière-plan pouvant être dessiné à une vue de texte dans un adaptateur de liste. J'ai un fond dessinable défini en XML commeComment modifier la couleur d'arrière-plan d'une ressource pouvant être dessinée par programmation

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > 
    <solid android:color="@color/black" /> 
    <stroke android:width="1dip" android:color="#ffffff"/> 
</shape> 

Je reçois cet élément drawable dans mon activité comme celui-ci

Drawable mDrawable = mContext.getResources().getDrawable(R.drawable.back); 

et maintenant j'ai différentes chaînes de codes hexadécimaux que je veux aussi changer l'arrière-plan mais je ne sais pas comment le faire. Filtre de couleur ou quelque chose?

Répondre

2

Une approche est la suivante:

public class MyDrawable extends ShapeDrawable{ 

      private Paint mFillPaint; 
      private Paint mStrokePaint; 
      private int mColor; 

      @Override 
      protected void onDraw(Shape shape, Canvas canvas, Paint paint) { 
       shape.drawPaint(mFillPaint, canvas); 
       shape.drawPaint(mStrokePaint, canvas); 
       super.onDraw(shape, canvas, paint); 
      } 

      public MyDrawable() { 
       super(); 
       // TODO Auto-generated constructor stub 
      } 
      public void setColors(Paint.Style style, int c){ 
       mColor = c; 
       if(style.equals(Paint.Style.FILL)){ 
        mFillPaint.setColor(mColor);      
       }else if(style.equals(Paint.Style.STROKE)){ 
        mStrokePaint.setColor(mColor); 
       }else{ 
        mFillPaint.setColor(mColor); 
        mStrokePaint.setColor(mColor); 
       } 
       super.invalidateSelf(); 
      } 
      public MyDrawable(Shape s, int strokeWidth) { 
       super(s); 
        mFillPaint = this.getPaint(); 
        mStrokePaint = new Paint(mFillPaint); 
        mStrokePaint.setStyle(Paint.Style.STROKE); 
        mStrokePaint.setStrokeWidth(strokeWidth); 
        mColor = Color.BLACK; 
      } 

     } 

Utilisation:

MyDrawable shapeDrawable = new MyDrawable(new RectShape(), 12); 
//whenever you want to change the color 
shapeDrawable.setColors(Style.FILL, Color.BLUE); 

Ou essayez, la seconde approche, jetant le dessinable ShapeDrawable, créer séparément Paint et mettez-le avec comme: castedShapeDrawable.getPaint().set(myNewPaint);

Questions connexes