Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextCompat.GetColor not returning Color

I'm trying to replace Resources.GetColor with ContextCompat.GetColor but the last one does not return a color and I don't get what should i use instead of Resources.GetColor(which became deprecated from API 23). Can anyone help me (see below what I want to achieve)?

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

Note that I use Xamarin, but if you have answer in java I can easily adapt it. Thank you!

like image 316
Alexandru Stefan Avatar asked Nov 19 '15 12:11

Alexandru Stefan


1 Answers

ContextCompat just returns an integer representation of your color. You need to convert it to an Android color by splitting its RGB parts up. 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);
like image 105
leonard_deutsch Avatar answered Nov 10 '22 01:11

leonard_deutsch