如何以编程方式更改可绘制资源背景颜色

时间:2013-08-28 01:53:43

标签: android android-layout android-canvas

我正在尝试将可绘制背景应用于列表适配器中的文本视图。我有一个可绘制的背景,在xml中定义为

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

我在我的活动中得到了这个可绘制元素

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

现在我有各种十六进制代码字符串,我想改变背景,但不知道怎么做。彩色滤光片还是什么?

1 个答案:

答案 0 :(得分:2)

一种方法是:

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

        }

用法:

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

或尝试第二种方法,将Drawable投射到ShapeDrawable,创建单独的Paint并将其设置为:castedShapeDrawable.getPaint().set(myNewPaint);

相关问题