Home > database >  how to change the stroke colour programatically in Android
how to change the stroke colour programatically in Android

Time:08-15

I have a constraintLayout with a style set to it, I want to be able to change. the stroke colour programatically.

what I tried

  val drawable = navigatorLayout.background as GradientDrawable
    drawable.mutate()

but got an error

android.graphics.drawable.LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable

Fragment

 val drawable = navigatorLayout.background as GradientDrawable
   drawable.mutate()
   drawable.setStroke(3, getColor(R.color.colorSecondary));

constraint layout

                    <androidx.constraintlayout.widget.ConstraintLayout
                        android:id="@ id/navigatorLayout"
                        android:layout_width="match_parent"
                        android:layout_height="40dp"
                        style="@style/SpinnerRounded"
                        android:layout_margin="@dimen/margin_vertical_small"
                        app:layout_constraintTop_toBottomOf="@ id/rgStats"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintEnd_toEndOf="parent">

SpinnerRounded

<style name="SpinnerRounded" parent="Spinner">
        <item name="android:background">@drawable/spinner_rounded_bg</item>
        <item name="android:paddingEnd">16dp</item>
        <item name="android:paddingStart">16dp</item>
    </style>

spinner_rounded_bg

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/grayish_blue"/>
            <corners android:radius="26dp"/>
            <stroke android:width="3dip" android:color="@color/grayish_blue" />
        </shape>
    </item>
</layer-list>

Please suggest what is the better way to change the stroke colour

Thanks R

CodePudding user response:

1)spinner_rounded_bg. Remove layerlist.And make it as parent. Because it would create a layout drawable.As per your code layer_list not required here.

 <shape android:shape="rectangle">
            <solid android:color="@color/grayish_blue"/>
            <corners android:radius="26dp"/>
            <stroke android:width="3dip" android:color="@color/grayish_blue" />
        </shape>

2)If you need layerlist to be added in xml,you can do like this while setting stroke.

(drawable as? LayerDrawable?)?.let {
    getDrawable(0)?.setStroke(3, getColor(R.color.colorSecondary));
}
  • Related