Android: Get Color object from Resource - android

Color color = new Color(context.getResources().getColor(R.color.bus_departures_hover));
As seen, I am attemping to create a Color object from a resource. This ain't working though!

What has worked for me is:
Color c = new Color(ContextCompat.getColor(context, R.color.yourColor));

Kotlin way (API REQUIRED 26);
Color.valueOf(ContextCompat.getColor(context, R.color.color_white))

It seems there's no API constructor that receives an int http://developer.android.com/reference/android/graphics/Color.html#Color()
You may use
int color= getResources().getColor(R.color.bus_departures_hover);
And use the color value in a setter.

Related

Android - Color taken from custom attribute returns a different value than same color from colors.xml

I have a custom layout that has custom attributes, one of them being a color. I have users set this attribute to a color (not a common color) and I use TypedArray's getColor method to retrieve this color and set it to an integer (if I print this int out, it is negative). Let's say I do something like this:
int myColor;
TypedArray ta = getContext().getTheme().obtainStyledAttributes(attrs, R.styleable.MyView, 0, 0);
myColor = ta.getColor(R.styleable.MyView_myColor, -1);
if (myColor == R.color.special_shade_of_yellow) {
mySpecialMethod()
}
Now let's say a user sets the attribute to be R.color.special_shade_of_yellow. However, the if block never goes through so mySpecialMethod() never gets called. For some reason, myColor is a negative value, while R.color.special_shade_of_yellow isn't. Why aren't they returning the same values? Thanks!
Colors in Android can be slightly confusing. You have color resource identifiers (like R.color.my_color) and you have color values (like 0xff0000), but both are represented by an int value.
TypedArray.getColor() will return a color value, i.e. a real color that you can directly apply to a view. Therefore, it's not something you'll want to compare to R.color.special_shade_of_yellow with a simple ==.
Try this instead:
if (myColor == ContextCompat.getColor(getContext(), R.color.special_shade_of_yellow)) {
...
}
ContextCompat.getColor() will resolve your color resource identifier (here R.color.special_shade_of_yellow) to a color value, and then you can perform an == comparison.

How to programmatically get value of built-in resources like colorAccent?

How do you get the actual value of a referenced color. In a layout I can use the following...
android:textColor="?android:attr/colorAccent"
..and this works in setting the text color of a TextView to the theme defined accent color. How do I get the value of the colorAccent using code at runtime?
Also, how do you discover a list of all the available values, there must be a long list of available colors I could get hold of, but where is that list defined?
If the resource is an Android defined one:
var id = Android.Resource.Attribute.ColorAccent;
If the resource is within a Dialog, Widget, etc.. that is not an Android system resource (i.e. to obtain a DatePickerDialog resource)
var id = SomeDatePickerDialog.Resources.GetIdentifier("date_picker_header_date", "id", "android");
Using the id obtained:
var typedArray = Theme.ObtainStyledAttributes(new int[] { id });
var color = typedArray.GetColor(0, int.MaxValue);
if (color != int.MaxValue)
{
Log.Debug("COLOR", color.ToString());
}
The R list changes with API/Theme, for the base values available:
Colors: https://developer.android.com/reference/android/R.color.html
Styles: https://developer.android.com/reference/android/R.style.html
etc...
But for a complete reference you have to use the Android source for the API the you are looking at:
https://android.googlesource.com/platform/frameworks/base/
So the colors that are defined in the Oreo beta:
https://android.googlesource.com/platform/frameworks/base/+/android-8.0.0_r4/core/res/res/color/
Then look within the specific color xml file for the how it is defined and use that definition to find the actual value of it (in one on the valueXXX files....)
For the example you have you can get that value with something like this:
//default color instead the attribute is not set.
var color = Color.Blue;
var attributes = new int[] { Android.Resource.Attribute.ColorAccent };
var typeArray = ObtainStyledAttributes(attributes);
//get the fist item (we are sending only one) and passing
//the default value we want, just in case.
var colorAccent = typeArray.GetColor(0, color);
colorAccent will have the Color set in your Theme for the ColorAccent attribute if any or the default value .
Important to mention that this method ObtainStyledAttributes is part of a Context so if you are already in an Activity you will find it as part of it but if you are in any other class you will need to pass in the context in case it's not available.
For the full list of available values you can get it from the Android.Resource.Attribute class. In VS do an inspection to see the different properties this class has. Maybe Android documentation has a better way though.
Hope this helps.-

explain the main reason to use getColor() method from ContextCompat class?

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
int color = ContextCompat.getColor(getContext(), mColorResourceId);
linearLayout.setBackgroundColor(color);
i have these line of code :
mColorResourceId it's hold R.color.category_numbers -> mColorResourceId = R.color.category_numbers
when i pass mColorResourceId directly to setBackgroundColor(mColorResourceId); it's doesn't change the color despite the method accept int value .
my question why i need this extra step int color = ContextCompat.getColor(getContext(), mColorResourceId); to change the color ??
The setBackgroundColor() method accepts an int that is supposed to be a color value in aarrggbb format. The resource ID R.color.category_numbers is also an int, but it is not a color value; instead it is the identifier of a color resource. Calling ContextCompat.getColor(getContext(), mColorResourceId) retrieves the actual color value corresponding to mColorResourceId.
Part of the reason Android does this kind of indirection is to provide flexibility. The actual color returned may depend on the current theme or the device configuration and may actually change at run time (depending on how you declare your color resource).

Android setTextColor not working

i'm trying to colorize text in textView using:
int color = getResources().getColor(R.color.green);
streetTv.setTextColor(color);
But this not working (i got null pointer exception)
But if i tried to:
textView.setBackgroundColor(Color.parseColor("#bdbdbd"));
This works.
Where can be problem?
just use something like this:
streetTv.setTextColor(Color.BLUE); //or any other color available
i don't think you actually need the resources in your case, because you didn't mention so.
Simply just set it directly.
streetTv.setTextColor(getResources().getColor(R.color.green));
Also as Raghunandan said, did you initialize streetTv?
have you declared
streetTv = findViewById(R.id.yourtextview);
before changing background color.

How to set ImageView using the name String of the local resource avoiding conditional mapping of resources

I want to set an ImageView programatically, passing the name of the local resource drawable as String.
The drawable clearly are int identified in this way
R.drawable.mydrawable_name
How could I do to solve this problem without map everything in a conditional switch?
I want to avoid something in this form
if(myString.equal"stringname_1"){
myImageview.setImageResource( R.drawable.stringname_1);
}
else if(myString.equal"stringname_1")....
etc
You can use getResources().getIdentifier() (http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)) for this purpose. For your code it would look something like this:
int id = getResources().getIdentifier(myString, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);
myImageview.setImageDrawable(drawable);
The code above assumes you're in an Activity.
You can do it using java reflection
Field field = R.drawable.class.getDeclaredField("mydrawable_name");
int a = field.getInt(this);
a will have the id value of R.drawable.mydrawable_name . Now you can use this id to set image
Pl Note: Below one is need to be comment for the accepted answer but I dont have previlage to add comment.
getDrawable(id) is deprecated now instead we can use
getDrawable(int id, Resources.Theme theme)
Return a drawable object associated with a particular resource ID and styled for the specified theme.
getTheme return the current theme.
Sample is given below:
Drawable drawable = resources.getDrawable(id, context.getTheme());

Categories

Resources