0

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.

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

1 Answer 1

6

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", "#"))
Sign up to request clarification or add additional context in comments.

2 Comments

I tried it and still through error NumberFormatException: For input string: "#FFAC235E". I think problem is not using 0x or #, it can't convert string to Int
I have edited my answer. Use Color.parseColor

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.