以编程方式设置安卓形状颜色

问题描述 投票:0回答:19

我正在编辑以使问题更简单,希望有助于准确回答。

说我有以下

oval
形状:

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

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

android android-layout shapes
19个回答
306
投票

注意:答案已更新以涵盖

background
ColorDrawable
的实例的场景。感谢Tyler Pfaff,指出这一点。

drawable 是一个椭圆,是 ImageView 的背景

使用

Drawable
imageView
获取
getBackground()

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 加载的可绘制对象共享相同的状态。)


76
投票

如今更简单的解决方案是使用您的形状作为背景,然后通过以下方式以编程方式更改其颜色:

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

有关可用选项,请参阅PorterDuff.Mode

更新(API 29):

自 API 29 以来,上述方法已被弃用,并由以下方法代替:

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

有关可用选项,请参阅BlendMode


50
投票

这样做:

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

23
投票

这个问题不久前得到了回答,但它可以通过重写为 kotlin 扩展函数来实现现代化。

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

16
投票

试试这个:

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

有关更多详细信息,请查看此链接this

希望有所帮助。


15
投票

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

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

12
投票

扩展 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");
    }

}

7
投票

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

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

7
投票

对我来说没什么用,但是当我设置色调颜色时,它适用于 Shape Drawable

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

需要 android 5.0 API 21


3
投票

我的 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")
    }
}

2
投票

Radius填充形状的简单方法是:

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

1
投票

可能是我来晚了。但是如果你使用的是 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)

享受....


1
投票

这可能有帮助

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>
  1. 将形状设置为视图的背景

  2. 设置您喜欢的颜色如下:

    Drawable bg = view.getBackground();
    bg.setColorFilter(Color.parseColor("#Color"), PorterDuff.Mode.ADD);
    

1
投票

我需要在我的适配器中执行此操作,但上面的解决方案要么不起作用,要么需要 >= android 版本 10。下面的代码对我有用!

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

0
投票

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

0
投票

更改自定义可绘制对象的纯色的最佳方法是 对于科特林。

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

0
投票

我们可以创建这个 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")

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

layout.setBackgroundDrawable(gd);

0
投票

对于 compileSdkVersion 33 的 2023 年,接受的答案在某种程度上起作用了。我的形状是复杂视图的简单圆形边框

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <stroke
        android:width="2dp"
        android:color="@color/white"/>
    <corners
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomLeftRadius="10dp"/>
</shape>

形状在名为

background
的视图中设置为
VScroll
。我需要形状的颜色与主题视图相同,所以我调整了接受的答案:

val lineBackground = binding.vScroll.background as GradientDrawable
lineBackground.setStroke(5,Color.parseColor(line.color))

其中

line.color
是一个十六进制字符串值,如
#FFFFFF
stroke width
的 int 值以像素为单位设置,因此必须将其转换为
dp
以获得正确的大小。

© www.soinside.com 2019 - 2024. All rights reserved.