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

假设我有如下椭圆形状:

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

享受……

其他回答

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

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

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

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

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

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

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。