If i defined a color in resources
#123456
it\'s possible
It works for me!
String.format("#%06x", ContextCompat.getColor(this, R.color.my_color) & 0xffffff)
Add @SuppressLint("ResourceType") if an error occurs. Like bellow.
private String formatUsernameAction(UserInfo userInfo, String action) {
String username = userInfo.getUsername();
@SuppressLint("ResourceType") String usernameColor = getContext().getResources().getString(R.color.background_button);
return "<font color=\""+usernameColor+"\">" + username
+ "</font> <font color=\"#787f83\">" + action.toLowerCase() + "</font>";
}
Just for the sake of easy copypasta:
"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color));
Or if you want it without the transparency:
"#" + Integer.toHexString(ContextCompat.getColor(getActivity(), R.color.some_color) & 0x00ffffff);
All of the solutions here using Integer.toHexString()
break if you would have leading zeroes in your hex string. Colors like #0affff
would result in #affff
. Use this instead:
String.format("#%06x", ContextCompat.getColor(this, R.color.your_color) & 0xffffff)
or with alpha:
String.format("#%08x", ContextCompat.getColor(this, R.color.your_color) & 0xffffffff)
Cause getResources().getColor
need api > 23. So this is better:
Just for the sake of easy copy & paste:
Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) );
Or if you want it without the transparency:`
Integer.toHexString( ContextCompat.getColor( getContext(), R.color.someColor ) & 0x00ffffff );