codepurveyor
codepurveyor

Reputation: 53

How do I set color with .setBackgroundColor(); with color from values/colors.xml

In Android, I'm trying to set a color from res/values/colors.xml

Using title.setBackgroundColor()

Currently I can set it with: title.setBackgroundColor(Color.GREEN);

However, I would like to reference a color from the .xml

When I use:

title.setBackgroundColor(R.color.white);

referring to:

<color name="white">#FFFFFF</color>

Andriod studio reports:

Should pass resolved color instead of resource id here: `getResources().getColor(R.color.white)` less... (⌘F1) 
This inspection looks at Android API calls that have been annotated with various support annotations (such as RequiresPermission or UiThread) and flags any calls that are not using the API correctly as specified by the annotations.  Examples of errors flagged by this inspection:
Passing the wrong type of resource integer (such as R.string) to an API that expects a different type (such as R.dimen).
Forgetting to invoke the overridden method (via super) in methods that require it
Calling a method that requires a permission without having declared that permission in the manifest
Passing a resource color reference to a method which expects an RGB integer value.
...and many more.  For more information, see the documentation at http://developer.android.com/tools/debugging/annotations.html

Upvotes: 1

Views: 7548

Answers (5)

Sheriff
Sheriff

Reputation: 868

You can try in Xamarin

SomeView.SetBackgroundResource(Resource.Color.justRed);

Upvotes: 0

ali farooq
ali farooq

Reputation: 1

Just add this

title.setBackground(getResources().getColor(R.color.yourcolor));

or

title.setBackgroundResource(R.color.yourColor);

Upvotes: -1

Augusto
Augusto

Reputation: 4233

Go to res->values->color.xml and write the code like below:

colors.xml

<resources>
    <color name="name_color">#3F51B5</color>
</resources>

And to set:

title.setBackgroundResource(R.color.name_color);

enter image description here

Upvotes: 4

Ian Rehwinkel
Ian Rehwinkel

Reputation: 2615

You need to use ContextCompat.getColor(getContext(), R.color.green). That will give you the color that you want, by the ID that you pass. In the end:

title.setBackgroundColor(ContextCompat.getColor(getContext, R.color.green));

Upvotes: 0

manhtuan21
manhtuan21

Reputation: 3430

In your xml file :

<color name="newcolor">#FF00</color>

and use

title.setBackgroundResource(R.color.newcolor);

Upvotes: 1

Related Questions