如何使用 Kotlin 或 Java 更改可绘制对象的笔触颜色



我有一个可绘制对象,用于设置线性布局的背景,将带有圆形的线性与半透明的橙色线一起保留。 但是在代码中的某个时刻,我需要将此背景(可绘制对象(的颜色更改为我仅作为参数的颜色,并且我的颜色文件的颜色中没有它。我需要将此可绘制对象的笔触颜色更改为我在运行时变量之一中的颜色

bg_static_show_password.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <!-- center circle -->
    <stroke android:color="@color/accent_color_alpha"
            android:width="3dp" />
    <solid android:color="@android:color/transparent" />
    <size
        android:width="28dp"
        android:height="28dp"/>
</shape>

线性布局

<android.support.constraint.ConstraintLayout
                        android:id="@+id/card_show_password"
                        android:layout_width="@dimen/anim_layout_size"
                        android:layout_height="@dimen/anim_layout_size"
                        android:layout_marginTop="@dimen/anim_margin_top"
                        android:background="@drawable/bg_static_show_password"
                        android:layout_gravity="center"
                        app:layout_constraintTop_toBottomOf="@id/view_group_item"
                        app:layout_constraintLeft_toLeftOf="parent"
                        app:layout_constraintRight_toRightOf="parent">

我正在尝试用来进行这种颜色更改的方法

fun showAlternativeForAnimation(view: LinearLayout) {
        val drawable = view.background as GradientDrawable
        val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
        drawable.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))
    }

方法的参数是线性布局

当我尝试时,我得到这个异常:科特林。TypeCastException:null 不能转换为非 null 类型 android.graphics.drawable.GradientDrawable

进行安全投射(as?(,确保您传递的视图具有形状可绘制对象集作为其背景,并将参数更改为view: View以允许用于任何视图(线性布局、约束布局等(。

fun showAlternativeForAnimation(view: View) {
    val drawable = view.background as? GradientDrawable
    val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
    drawable?.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))
}

最新更新