更改可绘制对象的按钮颜色后,我的笔划消失了,我无法再次设置笔划

After changing button color of drawable my stroke is gone and I cannot set the stroke again

我正在更改我的一个按钮的颜色,它是一个可绘制的形状,但它删除了笔划。我尝试再次设置笔画,但它不起作用。

它需要可变,因为我将此形状与其他按钮一起使用

Activity:

val bottomButton: Button = this.bottomButton
val drawable = bottomButton.getBackground() as GradientDrawable
drawable.mutate().setColorFilter(backBtnColor,PorterDuff.Mode.SRC_OVER)
drawable.setStroke(5,lightBgColor)

XML 可绘制:

<?xml version="1.0" encoding="UTF-8"?>
<shape
        xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
            android:width="5dp"
            android:color="@color/colorAccent"/>
    <corners
            android:radius="150dp" />

    <padding
            android:left="5dp"
            android:right="5dp"
            android:top="20dp"
            android:bottom="20dp"/>

    <solid android:color="@color/colorPrimary"/>

</shape>

我在 Layout 中设置了 drawable XML

<Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" android:id="@+id/bottomButton"
                    android:layout_marginHorizontal="24dp"
                    android:textSize="32dp"
                    android:layout_marginVertical="16dp"
                    android:background="@drawable/btn_rounded" tools:text="Options" android:text="Options"/>

结果是新颜色填充了整个按钮(颜色变化很好)但是它删除了描边。我想要新颜色,但保留笔触,或者至少让我将笔触设置回原来的。

我找到答案了:

在 Activity 文件中:

val backBtnColor:Int = getResources().getColor(R.color.colorPrimaryDark)
val bottomButton: Button = this.bottomButton
val drawable = bottomButton.getBackground().mutate() as GradientDrawable
drawable.setColor(backBtnColor)

关键是在声明的时候把mutate()加到val drawable上,而不是后面调用​​的时候。这使您能够 setColor(),这是您需要的 属性。