ContextCompat.GetColor does not return color

I am trying to replace Resource.GetColor with ContextCompat.GetColor, but the latter does not return color, and I do not get what I should use instead of Resource.GetColor (which has become deprecated from API 23). Can someone help me (see below what I want to achieve)?

Button.SetBackgroundColor(ContextCompat.GetColor(this, Resource.Color.LightRed)); 

Please note that I am using Xamarin, but if you have an answer in java, I can easily adapt it. Thanks!

+7
android android-6.0-marshmallow xamarin
source share
2 answers

ContextCompat simply returns an integer representation of your color. You need to convert it to Android color by separating its parts from RGB. Use something like this

 using Android.Graphics; public static Color GetColorFromInteger(int color) { return Color.Rgb(Color.GetRedComponent(color), Color.GetGreenComponent(color), Color.GetBlueComponent(color)); } 

and in your method

 btn.SetBackgroundColor(GetColorFromInteger(ContextCompat.GetColor(this, Resource.Color.LightRed); 
+1
source share

I had the same problem, I think, and resolved it by adding the @SuppressWarnings("ResourceAsColor") annotation on top of the method.

The reason is that, in my opinion, Lint does not recognize the new API at the moment, although it is valid. Both methods return an integer that represents the allowed color. In my tests, Resources.GetColor () and ContextCompat.GetColor () return the same value. However, when using the latter, I get an error message in Android Studio:

 Should pass resolved color instead of resource id here: `getResources().getColor(titleColor)` 

... which does not make sense because I am missing the allowed color. This is just int , since I could be wrong ... Therefore, in conclusion, I believe that suppressing Lint Error is a valid way to handle the situation at the moment.

If you do not agree, please raise your voice, I would be interested.

0
source share

All Articles