以编程方式设置android形状颜色

Cot*_*nyo 149 android shape android-layout

我正在编辑以使问题更简单,希望这有助于获得准确的答案.

说我有以下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>
Run Code Online (Sandbox Code Playgroud)

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

Vik*_*ram 248

注意:答案已更新,以涵盖background作为实例的场景ColorDrawable.感谢Tyler Pfaff指出这一点.

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

DrawableimageView使用中获取getBackground():

Drawable background = imageView.getBackground();
Run Code Online (Sandbox Code Playgroud)

检查通常的嫌疑人:

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));
}
Run Code Online (Sandbox Code Playgroud)

紧凑版:

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));
}
Run Code Online (Sandbox Code Playgroud)

请注意,不需要进行空检查.

但是,mutate()如果在其他地方使用它们,则应在修改之前使用drawables.(默认情况下,从XML加载的drawable共享相同的状态.)

  • 谢谢回答.(+1).我的代码遇到了其他错误,所以很难测试.但是这仍然可以设置形状的"固体"部分."笔画"部分怎么样? (3认同)
  • android.graphics.drawable.GradientDrawable无法强制转换为android.graphics.drawable.ShapeDrawable转换失败了 (3认同)
  • @John如果``ImageView'的背景设置为`GradientDrawable`,`getBackground()`将不会返回`ShapeDrawable`.相反,使用返回的`GradientDrawable`:`GradientDrawable gradientDrawable =(GradientDrawable)imageView.getBackground();`....`gradientDrawable.setColors(new int [] {color1,color2});`. (3认同)
  • 谢谢..救了我的世界. (2认同)

Leo*_*y91 42

这样做:

    ImageView imgIcon = findViewById(R.id.imgIcon);
    GradientDrawable backgroundGradient = (GradientDrawable)imgIcon.getBackground();
    backgroundGradient.setColor(getResources().getColor(R.color.yellow));
Run Code Online (Sandbox Code Playgroud)


Gio*_*gos 27

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

PorterDuff.Mode.SRC_ATOP

  • 正确的是:`view.getBackground()。setColorFilter(Color.parseColor(“#343434”),PorterDuff.Mode.SRC_ATOP);`由于背景上可能有边框或圆角。 (4认同)
  • 将“BlendModeColorFilter”设置为“PorterDuff.Mode”将无法编译,因为它需要“BlendMode”。因此,对于 API 29,它应该是 `view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)`。 (2认同)

and*_*qq6 13

试试这个:

 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);
 }
Run Code Online (Sandbox Code Playgroud)

为更详细检查此链接

希望有所帮助


med*_*hdj 12

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

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);
Run Code Online (Sandbox Code Playgroud)


Tyl*_*aff 11

扩展Vikram的答案,如果你要着色动态视图,如回收者视图项等等.那么你可能想在设置颜色之前调用mutate().如果不这样做,任何具有共同drawable(即背景)的视图也将更改/着色其drawable.

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

}
Run Code Online (Sandbox Code Playgroud)

  • 需要和额外的检查和参数:`if (background instanceof LayerDrawable) { background = ((LayerDrawable) background.mutate()).getDrawable(indexIfLayerDrawable); } if (background instanceof ShapeDrawable)[...]` 处理使用 `&lt;layer-list ... &lt;item ...` 的背景布局。 (3认同)

Car*_*ino 10

这个问题在一段时间后得到了回答,但它可以通过重写作为kotlin扩展函数进行现代化.

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


Sum*_*mit 7

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

 Drawable background = imageView.getBackground();
 background.setTint(getRandomColor())
Run Code Online (Sandbox Code Playgroud)

需要安卓 5.0 API 21


小智 6

this is the solution that works for me...wrote it in another question as well: How to change shape color dynamically?

//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)
Run Code Online (Sandbox Code Playgroud)