Brian
Brian

Reputation: 4408

How do I programatically change a drawable resource's background color

I'm trying to apply a drawable background to a text view in a list adapter. I have a drawable background defined in xml as

<?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>

I get this drawable element in my activity like this

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

and now I have various strings of hex codes that I want to change the background too but not sure how to do it. Color filter or something?

Upvotes: 3

Views: 1770

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50538

One approach is this:

 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;
            }

        }

Usage:

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

Or try, the second approach, casting the Drawable to ShapeDrawable, create separate Paint and set it with like: castedShapeDrawable.getPaint().set(myNewPaint);

Upvotes: 3

Related Questions