简体   繁体   English

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

[英]Setting the color of a shape programmatically

I am trying to set the color of my shape programmatically, inside my drawable I created a rounded shape (rounded_button.xml):我试图以编程方式设置我的形状的颜色,在我的 drawable 中,我创建了一个圆形(rounded_button.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#00b248" />
    <corners android:bottomRightRadius="8dp"
        android:bottomLeftRadius="8dp"
        android:topRightRadius="8dp"
        android:topLeftRadius="8dp"/>
</shape>

And now I want to change it color in my activity.现在我想在我的活动中改变它的颜色。

public void setShapeColor() {
    Drawable shapeDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.rounded_button, null);
    shapeDrawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}

But it does not work and holds still the same color.但它不起作用并且仍然保持相同的颜色。

This how you can change color defined drawable in xml这是如何更改 xml 中定义的可绘制颜色的方法

LayerDrawable shapeRectangle = (LayerDrawable) getDrawable(context, R.drawable.custom_layer);
GradientDrawable gradient = (GradientDrawable) shapeRectangle.findDrawableByLayerId(R.id.shape_rectangle);
gradient.setColor(Color.RED);

Try to use tint to made tint of drawable.尝试使用 tint 使可绘制的色调。

example:例子:

fun getTintDrawable(context:Context, resId: Int, tint: Int): Drawable? {
    val normalDrawable = ContextCompat.getDrawable(context, resId)
    var wrapDrawable = if (normalDrawable == null) null else DrawableCompat.wrap(normalDrawable)

    if (wrapDrawable != null) {
        DrawableCompat.setTint(wrapDrawable, tint)
    }

    return wrapDrawable
}

Sorry that i use kotlin, but rewrite to java could not take so much time.抱歉,我使用 kotlin,但重写为 java 不会花费太多时间。 Hope it helps.希望能帮助到你。

BR BR

@Nullable
public Drawable getTintDrawable(Context context, int resId, int tint) {
    Drawable normalDrawable = ContextCompat.getDrawable(context, resId);
    Drawable wrapDrawable = (normalDrawable == null) ? null : DrawableCompat.wrap(normalDrawable);

    if (wrapDrawable != null) {
        DrawableCompat.setTint(wrapDrawable, tint);
    }

    return wrapDrawable;
}

As requested by @Jonnotdoexx根据@Jonnotdoexx 的要求

Same code in Java: Java中的相同代码:

Please note that this function will return null if first if clause fail to execute.请注意,如果第一个if子句执行失败,此函数将返回 null。

Drawable getTintDrawable(Context context, int resId, int tint) {
    Drawable normalDrawable = ContextCompat.getDrawable(context, resId);
    Drawable wrapDrawable;
    if (normalDrawable != null) 
        wrapDrawble = DrawableCompat.wrap(normalDrawable);
    if (wrapDrawable != null) 
       DrawableCompat.setTint(wrapDrawable, tint);
    return wrapDrawable;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM