Lampione
Lampione

Reputation: 1608

Convert int value to res/color

This may be a very specific question because I didn't find anything related. Also, sorry if I couldn't find a better title.

I'm working with android colors, specifically, I'm in a situation where I need to let the user programmatically change color of a view.

I'll give some values and example so that you can undestand better my case.

In my res/colors.xml I have this color_green with value #4CAF50. As soon as the activity starts, I set this color to a view. In order so set the color,I'm first converting it to a String hex color as:

int color = myGreenColor; // This is directly taken from resource so R.color.green_color, (2131427355)
int value = ContextCompat.getColor(context, color); // (-11751600)
String hexColor = String.format("#%06X", (value)); // (#FF4CAF50)

then I set it to the view with

mView.setBackgroundColor(Color.parseColor(hexColor));// (-11751600) again

Now, the myGreenColor value is changed as the user pick another color from the pes8 ColorPicker library found at this link

Let's say I pick the exact same value which I pass to the constructor of the library in R, G, B ints.

If I print the returned value from the dialog, I get something like

-11751600.

Which I couldn't fit into any set, parse or other method. That said, how can I convert this value in order to work with the previous conversions?

I need to convert from format -11751600 to format 2131427355. or any other intermediate step value.

Any help would really be appreciated.

Upvotes: 1

Views: 1373

Answers (1)

Akash Singh
Akash Singh

Reputation: 751

If you have the RGB values you can directly do this to :

String color = "#" + RR + GG + BB;

Then set this color to your view using

mView.setBackgroundColor(Color.parseColor(color))

Color.parseColor(String) supports #RRGGBB #AARRGGBB format colors. You can check the documentation here Android documentation

Upvotes: 1

Related Questions