Home > Back-end >  Cannot access colors from resources via R.color.x
Cannot access colors from resources via R.color.x

Time:09-06

I have created a color list under values/colors.xml with the following content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorConnected">#FFFFFF</color>
</resources>

When trying to use the color from my code like this:

context?.getColor(R.color.colorConnected)

The compiler cannot resolve the color name:

Unresolved reference: colorConnected

PS: Using the color in other XML files works fine (e.g. "@color/colorConnected").

CodePudding user response:

Go to the top(in imports section) and

  1. find import .....R and remove it.
  2. move to the place where R is being used, it must be Red colored.
  3. Click on the R and import.

This will solve your issue.

CodePudding user response:

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

OR

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

OR

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

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