Search code examples
javaandroidkotlindrawable

How to change stroke color of a drawable with Kotlin or Java


I have a drawable object that I use to set the background of a linear layout, leaving the linear with the circular shape with a semi transparent orange line. but at some point in the code I need to change the color of this background (drawable object) to a color that I have only as a parameter and I don't have it in the colors of my color file. I need to change the stroke color of this drawable to a color that I have in one of my runtime variables

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>

linear layout

<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">

method I'm trying to use to make this color change

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

    }

the parameter of method is the LinearLayout

When I try, I get this exception: kotlin.TypeCastException: null cannot be cast to non-null type android.graphics.drawable.GradientDrawable


Solution

  • Make a safe cast (as?), ensure that the view you pass has a shape drawable set as it's background and change parameter to view: View so as to allow usage for any view(LinearLayout, ConstraintLayout, etc).

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