1

I have created following drawable and set it to a button background from code.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="8dp"/>
    <solid android:color="@color/background_profile"/>
    <padding android:left="8dp" android:top="7dp" android:right="8dp" android:bottom="6dp" />
</shape>

Kotlin File

  btn?.background= resources?.getDrawable(R.drawable.drawable_rewards)

Now i will be getting color from my service, like this "#00000", and I need to update the color in drawable_rewards.xml file.

Is there any way we can change color of drawable file dynamically.

1
  • 1
    You could use a MaterialButton (which has as default rounded corners) and use backgroundTint to change the background color. Commented Jul 6, 2020 at 10:01

3 Answers 3

1
    val wrappedDrawable: Drawable = DrawableCompat.wrap(ContextCompat.getDrawable(context!!, R.drawable.drawable_rewards)!!)
    DrawableCompat.setTint(wrappedDrawable, ContextCompat.getColor(context!!, R.color.colorPrimary))
    btn?.background = wrappedDrawable
Sign up to request clarification or add additional context in comments.

Comments

1

The answer is you get background of the button as drawable -> change color of drawable -> set drawable to background of the button

            val drawable: Drawable = buttonChange.background
            drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC)
            buttonChange.background = drawable

Comments

0
fun View.setBgColor(color: String?) {
    val bgColor = parseColor(color) ?: return
    val drawable = if (background is InsetDrawable)
        (background as InsetDrawable).drawable
    else
        background

    when (drawable?.mutate()) { //mutate before change is important
        is ShapeDrawable -> (drawable as ShapeDrawable).paint.color = bgColor
        is GradientDrawable -> (drawable as GradientDrawable).setColor(bgColor)
        is ColorDrawable -> (drawable as ColorDrawable).color = bgColor
    }
}

fun parseColor(color: String?): Int? {
    return try {
        Color.parseColor(color)
    } catch (e: Exception) {
        null
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.