androidkotlinandroid-drawablerippledrawable

Change a particular color of a tag in a range of tags in drawable asset


I created a drawable asset to use it as a button. The code is shown below

round_button.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="@android:color/white">
    <item android:id="@+id/circle_border">
        <shape android:shape="oval">
            <solid android:color="@color/deep_orange_700"/>
            <stroke
                android:width="16dp"
                android:color="@color/login_register_tab_text" />
        </shape>
    </item>

</ripple>

This drawable asset is assigned to an Image Button

<ImageButton
    android:id="@+id/button_dnd"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/round_button"
    android:contentDescription="@string/description"
    android:padding="50dp"
    android:scaleX="0.7"
    android:scaleY="0.7"
    android:src="@drawable/src"
    />

So my question is how to change the color of the tag in the drawable asset, the tags <solid android:color="@color/deep_orange_700"/> and <stroke android:color="@color/login_register_tab_text" /> without affecting each other in kotlin file(dynamically)?

tldr: I tried to create an image button with a custom drawable asset and wanted to change the color dynamically whenever the button is pressed. But I couldn't change a particular color on the drawable file.


Solution

  • This is how you can change the colors on runtime

    val background = findViewById<ImageButton>(R.id.button_dnd).getBackground() as RippleDrawable
    val shapeDrawable = background.getDrawable(0) as GradientDrawable
    
    shapeDrawable.setStroke(strokeWidthPX, strokeColor)
    shapeDrawable.setColor(fillColor)