Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert String to int Color value

I want to set background with gradient. This’s my code:

val startColor = "0xFFAC235E"
val endColor = "0xFF640C35"
val gradient = GradientDrawable(
    GradientDrawable.Orientation.LEFT_RIGHT,
    intArrayOf(
        startColor.toInt(),
        endColor.toInt()
    )
)
view.background = gradient

and it through an exception:

java.lang.NumberFormatException: For input string: "0xFFAC235E"

If I replace startColor = 0xFFAC235E, the code above work fine. But that’s not what I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need put color as param String. Is there anyway to convert it?

>Solution :

Try replacing 0x with #.

For ex:

startColor.replace("0x", "#")

Generally we define colors with hex color codes. So, I think this will work for you.

Edit

You have to parse the color string to convert it into integer.

Color.parseColor(startColor.replace("0x", "#"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading