我正在编辑,使问题更简单,希望有助于得到一个准确的答案。

假设我有如下椭圆形状:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
    <solid android:angle="270"
           android:color="#FFFF0000"/>
    <stroke android:width="3dp"
            android:color="#FFAA0055"/>
</shape>

如何从一个活动类中以编程方式设置颜色?


试试这个:

 public void setGradientColors(int bottomColor, int topColor) {
 GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[]  
 {bottomColor, topColor});
 gradient.setShape(GradientDrawable.RECTANGLE);
 gradient.setCornerRadius(10.f);
 this.setBackgroundDrawable(gradient);
 }

要了解更多细节,请查看这个链接

希望有帮助。


注意:答案已经更新,以涵盖背景是ColorDrawable实例的场景。谢谢泰勒·普法夫指出这一点。

可绘制对象是一个椭圆形,是ImageView的背景

使用getBackground()从imageView获取Drawable:

Drawable background = imageView.getBackground();

检查通常的嫌疑:

if (background instanceof ShapeDrawable) {
    // cast to 'ShapeDrawable'
    ShapeDrawable shapeDrawable = (ShapeDrawable) background;
    shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    // cast to 'GradientDrawable'
    GradientDrawable gradientDrawable = (GradientDrawable) background;
    gradientDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    // alpha value may need to be set again after this call
    ColorDrawable colorDrawable = (ColorDrawable) background;
    colorDrawable.setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

简洁版:

Drawable background = imageView.getBackground();
if (background instanceof ShapeDrawable) {
    ((ShapeDrawable)background).getPaint().setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof GradientDrawable) {
    ((GradientDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
} else if (background instanceof ColorDrawable) {
    ((ColorDrawable)background).setColor(ContextCompat.getColor(mContext,R.color.colorToSet));
}

注意,空检查不是必需的。

但是,如果在其他地方使用可绘制对象,则应该在修改它们之前对它们使用mutate()。(默认情况下,从XML加载的可绘制对象共享相同的状态。)


这样做:

    ImageView imgIcon = findViewById(R.id.imgIcon);
    GradientDrawable backgroundGradient = (GradientDrawable)imgIcon.getBackground();
    backgroundGradient.setColor(getResources().getColor(R.color.yellow));

希望这对有同样问题的人有所帮助

GradientDrawable gd = (GradientDrawable) YourImageView.getBackground();
//To shange the solid color
gd.setColor(yourColor)

//To change the stroke color
int width_px = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, youStrokeWidth, getResources().getDisplayMetrics());
gd.setStroke(width_px, yourColor);

这是对我有效的解决方案……也写在另一个问题里: 如何动态改变形状颜色?

//get the image button by id
ImageButton myImg = (ImageButton) findViewById(R.id.some_id);

//get drawable from image button
GradientDrawable drawable = (GradientDrawable) myImg.getDrawable();

//set color as integer
//can use Color.parseColor(color) if color is a string
drawable.setColor(color)

扩展Vikram的答案,如果你是着色动态视图,如回收视图项目等....那么,在设置颜色之前,您可能需要调用mutate()。如果你不这样做,任何具有公共可绘制对象(即背景)的视图也将改变/着色它们的可绘制对象。

public static void setBackgroundColorAndRetainShape(final int color, final Drawable background) {

    if (background instanceof ShapeDrawable) {
        ((ShapeDrawable) background.mutate()).getPaint().setColor(color);
    } else if (background instanceof GradientDrawable) {
        ((GradientDrawable) background.mutate()).setColor(color);
    } else if (background instanceof ColorDrawable) {
        ((ColorDrawable) background.mutate()).setColor(color);
    }else{
        Log.w(TAG,"Not a valid background type");
    }

}

这个问题之前已经回答过了,但是可以通过重写为kotlin扩展函数来实现现代化。

fun Drawable.overrideColor(@ColorInt colorInt: Int) {
    when (this) {
        is GradientDrawable -> setColor(colorInt)
        is ShapeDrawable -> paint.color = colorInt
        is ColorDrawable -> color = colorInt
    }
}

现在一个更简单的解决方案是使用你的形状作为背景,然后通过编程改变它的颜色:

view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)

看到PorterDuff。可用选项的模式。

更新(api 29):

上述方法自API 29起已弃用,由以下方法取代:

view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)

有关可用选项,请参阅BlendMode。


用半径填充形状的简单方法是:

(view.getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN);

我没有工作,但当我设置色调颜色,它工作在形状绘制

 Drawable background = imageView.getBackground();
 background.setTint(getRandomColor())

需要android 5.0 API 21


我的Kotlin扩展函数版本基于上述答案与Compat:

fun Drawable.overrideColor_Ext(context: Context, colorInt: Int) {
    val muted = this.mutate()
    when (muted) {
        is GradientDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
        is ShapeDrawable -> muted.paint.setColor(ContextCompat.getColor(context, colorInt))
        is ColorDrawable -> muted.setColor(ContextCompat.getColor(context, colorInt))
        else -> Log.d("Tag", "Not a valid background type")
    }
}

对于任何使用c# Xamarin的人来说,这里是一个基于Vikram代码片段的方法:

private void SetDrawableColor(Drawable drawable, Android.Graphics.Color color)
{
    switch (drawable)
    {
        case ShapeDrawable sd:
            sd.Paint.Color = color;
            break;
        case GradientDrawable gd:
            gd.SetColor(color);
            break;
        case ColorDrawable cd:
            cd.Color = color;
            break;
    }
}

也许我来晚了。但是如果您正在使用Kotlin。有这样的方法

var gd = layoutMain.background as GradientDrawable

 //gd.setCornerRadius(10)
  gd.setColor(ContextCompat.getColor(ctx , R.color.lightblue))
  gd.setStroke(1, ContextCompat.getColor(ctx , R.color.colorPrimary)) // (Strokewidth,colorId)

享受……


改变自定义绘制的纯色的最好方法是 芬兰湾的科特林。

 (findViewById<TextView>(R.id.testing1).getBackground()).setColorFilter(Color.parseColor("#FFDE03"), PorterDuff.Mode.SRC_IN); 

这可能会有所帮助

1.最初将形状颜色设置为透明

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
   <solid android:angle="270"
       android:color="@android:color/transparent"/>
   <stroke android:width="3dp"
        android:color="#FFAA0055"/>
</shape>

将形状设置为视图的背景 设置你喜欢的颜色如下: 可绘制bg = view.getBackground(); bg.setColorFilter (Color.parseColor(“#颜色”),PorterDuff.Mode.ADD);


我需要在我的适配器中这样做,但上面的解决方案要么不工作,要么需要>= android版本10。下面的代码对我有用!

val drawable = DrawableCompat.wrap(holder.courseName.background)
DrawableCompat.setTint(drawable, Color.parseColor("#4a1f60"))

我们可以创建这个kotlin函数。

fun View.updateViewBGSolidColor(colorString: String) {
    when (val background: Drawable = this.background) {
        is ShapeDrawable -> {
            background.paint.color = Color.parseColor(colorString)
        }
        is GradientDrawable -> {
            background.setColor(Color.parseColor(colorString))
        }
        is ColorDrawable -> {
            background.color = Color.parseColor(colorString)
        }
    }
}

然后像下面这样使用它:

yourTextView.updateViewBGSolidColor("#FFFFFF")

GradientDrawable gd = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM,
        new int[] {0xFF616261,0xFF131313});
gd.setCornerRadius(0f);

layout.setBackgroundDrawable(gd);