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

标签 android android-layout android-canvas

我正在尝试将可绘制背景应用于列表适配器中的 TextView 。我有一个在 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>

我在我的 Activity 中得到这个可绘制元素,如下所示

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

现在我有各种十六进制代码字符串,我也想更改背景,但不知道该怎么做。滤色镜什么的?

最佳答案

一种方法是这样的:

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

关于android - 如何以编程方式更改可绘制资源的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18478210/

相关文章:

Android:广播接收器中的电话状态

android - Canvas /旋转/屏幕方向

android - Canvas 绘制比原始图片小的位图

android - 在 Android 应用程序中启动另一个应用程序

java - 将抽屉导航添加到空白 Activity

android - Oracle VM virtual box 中 dpi 的设置

Android:Honeycomb/Gingerbread 的不同小部件布局

android - ViewModel 不能在 Activity 中实例化

java - 如何将 Paint 或 Color 传递给使用 Activity 中的 onDraw() 方法的新对象?