Reputation: 25267
I have (unfortunately. Anyways..) color format which is used in html:
rgba(31,194,174,1)
I want to convert it to android native hex color format #AARRGGBB. Can anyone please help me with this.
I tried the following way, but it didn't worked:
...
tabLayout.setBackgroundColor(getTabLayoutBackgroundColor(jsonObject));
...
private int getTabLayoutBackgroundColor(JSONObject jsonObject) {
// tab color
String[] rgba_tab = new String[4];
try {
rgba_tab = jsonObject.getString("navbar-background-color").split("\\(")[1].split("\\)")[0].split(",");
} catch (JSONException e) {
e.printStackTrace();
}
return Color.argb(Integer.parseInt(rgba_tab[3]), Integer.parseInt(rgba_tab[0]), Integer.parseInt(rgba_tab[1]), Integer.parseInt(rgba_tab[2]));
}
I have to parse the following response to set colors dynamically to my controls like ToolBar, TabLayout background and TabLayout text colors:
{
"primary-color": "rgba(214,34,48,1)",
"background-color": "default",
"navbar-background-color": "rgba(214,34,48,1)",
"navbar-font-color": "rgba(255,255,255,1)",
"font": "Arial"
}
Upvotes: 0
Views: 3192
Reputation: 1332
Here is my function to convert color from rgba to android color format:
@ColorInt
int parseRgba(@NonNull String colorString, @ColorInt int defaultColor) {
String cs = colorString.replaceAll("\\s", "");
if (cs.startsWith("rgba(") && cs.endsWith(")")) {
String[] components = cs
.substring(5, cs.length() - 1)
.split(",");
if (components.length == 4) {
try {
int red = Integer.parseInt(components[0]);
int green = Integer.parseInt(components[1]);
int blue = Integer.parseInt(components[2]);
float alphaF = Float.parseFloat(components[3]);
if (0 <= red && red <= 255 &&
0 <= green && green <= 255 &&
0 <= blue && blue <= 255 &&
0f <= alphaF && alphaF <= 1f) {
return Color.argb((int) (alphaF * 255), red, green, blue);
}
} catch (NumberFormatException ignored) {
}
}
}
return defaultColor;
}
Upvotes: 0
Reputation: 3212
Try using:
String hex = String.format("#%02x%02x%02x%02x", alpha,red, green, blue);
Upvotes: 2
Reputation: 556
Try this: Color c = new Color(i,j,k); Integer.toHexString( c.getRGB() & 0x00ffffff ) );
Upvotes: 0