2013-08-28 70 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);

相關問題