How to Get Color-Int from Color Resource

How can I get color-int from color resource?

You can use:

getResources().getColor(R.color.idname);

Check here on how to define custom colors:

http://sree.cc/google/android/defining-custom-colors-using-xml-in-android

EDIT(1):
Since getColor(int id) is deprecated now, this must be used :

ContextCompat.getColor(context, R.color.your_color);

(added in support library 23)

EDIT(2):

Below code can be used for both pre and post Marshmallow (API 23)

ResourcesCompat.getColor(getResources(), R.color.your_color, null); //without theme

ResourcesCompat.getColor(getResources(), R.color.your_color, your_theme); //with theme

Get color resource as string

I think you missed #

Color.parseColor("#"+Integer.toHexString(ContextCompat.getColor(context, R.color.redish)))

Android - colors.xml resource to int value

The getColor() method of Resources returns the color in 0xAARRGGBB format;

int color = getResources().getColor(R.color.white); // color is now 0xFFFFFFFF
int alpha = Color.alpha(color);
int red = Color.red(color);
...

How to distinguish color int from color resource

There is the annotation @ColorInt for this purpose.

getResources().getColor() is deprecated

It looks like the best approach is to use:

ContextCompat.getColor(context, R.color.color_name)

eg:

yourView.setBackgroundColor(ContextCompat.getColor(applicationContext,
R.color.colorAccent))

This will choose the Marshmallow two parameter method or the pre-Marshmallow method appropriately.

Retrieving color programmatically from R.color returns wrong colors

That is the id of the colour, not the colour itself. To get the colour you need getResources().getColor(field.getInt(null)); instead.

Everything on R is an ID. That is why we have methods like getColor or getDrawable which take as argument R.color.my_color or R.drawable.my_drawable.

How do I use Color resource directly in Jetpack Compose?

You can use colorResource() which loads a color resource.

Text(
text = "Hello World",
color = colorResource(R.color.purple_200)
)


Related Topics



Leave a reply



Submit