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

假设我有如下椭圆形状:

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

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


当前回答

也许我来晚了。但是如果您正在使用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)

享受……

其他回答

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

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

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

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

试试这个:

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

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

希望有帮助。

对于任何使用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;
    }
}

这可能会有所帮助

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