Xamarin Android: getting color value from colors.xml programmatically
14,208
Solution 1
Problem was that I tried to access Resources from ListView Adapter. Solution is to use:
parent.Resources.GetColor(Resource.Color.row_a)
where parent
is passed into public override View GetView(int position, View convertView, ViewGroup parent)
method.
Solution 2
Try this code:
Color t = new Android.Graphics.Color (ContextCompat.GetColor (this, Resource.Color.row_a));
![Marcin Zdunek](https://i.stack.imgur.com/iOyqj.jpg?s=256&g=1)
Author by
Marcin Zdunek
I've been programming since 10, it's my passion for life. Besides I love music and I collect coins.
Updated on June 14, 2022Comments
-
Marcin Zdunek about 2 years
How can I get value of color programmatically from colors.xml file into C# code?
Here is my colors.xml:
<?xml version="1.0" encoding="utf-8" ?> <resources> <item name="row_a" type="color">#FFCCFFCC</item> <item name="row_b" type="color">#FFFFFFCC</item> <item name="all_text" type="color">#FF000000</item> <item name="row_red" type="color">#FFFF4444</item> <item name="row_orange" type="color">#FFE69900</item> <item name="row_green" type="color">#FF739900</item> <item name="wheat" type="color">#FFF5DEB3</item> <integer-array name="androidcolors"> <item>@color/row_a</item> <item>@color/row_b</item> <item>@color/all_text</item> <item>@color/row_red</item> <item>@color/row_orange</item> <item>@color/row_green</item> <item>@color/wheat</item> </integer-array> </resources>
I tried:
Color t = (Color)Resource.Colors.wheat;
but of course I cannot convert int value to Color this way.
EDIT:
As suggested I tried
Color t = Resources.GetColor(Resource.Color.row_a);
But it gives me an error:
Error CS0120 An object reference is required for the non-static field, method, or property 'Resources.GetColor(int)'
-
Jamshaid K. about 7 yearsThis method is depricated now, now you can do it this way
new Android.Graphics.Color(ContextCompat.GetColor(this, Resource.Color.color_name))
-
Shahzad Latif about 7 yearsContextCompat does not even contain GetColor method! any ideas?
-
Shahzad Latif about 7 yearsForget it. Updating the package Xamarin.Android.Support.V4 from NuGet fixed the issue. I was trying an old sample which contained an old version of the package so it was not showing up.
-
Pierre about 7 years
Android.Support.V4.Content.ContextCompat.GetColor(this, Resource.Color.my_color)
-
Rabadash8820 almost 6 years@CodeIt Out of curiosity, do you know why the
Resources.GetColor
method was deprecated? This newContextCompat
way of doing things seems extremely verbose -
Alan about 2 yearsEVERYTHING in Android is verbose. Look how much trouble it is to get a simple color when you want it. If we did our jobs the way they do theirs, we would be fired...