【问题标题】:After changing button color of drawable my stroke is gone and I cannot set the stroke again更改可绘制按钮颜色后,我的笔划消失了,我无法再次设置笔划
【发布时间】:2019-04-16 18:43:19
【问题描述】:

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

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

活动:

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>

我在布局 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"/>

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

【问题讨论】:

    标签: android kotlin drawable stroke


    【解决方案1】:

    我想出了答案:

    在活动文件中:

    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(),这是您需要的属性。

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多