2013-08-28 71 views
2

我试图将绘图背景应用于列表适配器中的文本视图。我在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); 

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

回答

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

或者试试,第二种方法,铸造可绘制到ShapeDrawable,创建单独的Paint,并设为:castedShapeDrawable.getPaint().set(myNewPaint);

相关问题