dobridog
dobridog

Reputation: 380

Resources NotFoundException getColor() that uses colorAccent attribute

Why can't this color be resolved programmatically:

Definition of the style.xml:

<style name="MyTheme.Light" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorAccent">#ff0000</item>
</style>

Definition of colors.xml:

<color name="button_color">?attr/colorAccent</color>    

Source:

getResources().getColor(R.color.button_color);

Throws the following exception:

android.content.res.Resources$NotFoundException: Resource ID #0x7f07001b type #0x2 is not valid
at android.content.res.Resources.getColor(Resources.java:752)
...

Upvotes: 4

Views: 1295

Answers (2)

TGruenwald
TGruenwald

Reputation: 166

TypedValue typedValue = new TypedValue();
TypedArray typedArray = context.obtainStyledAttributes(typedValue.data, new int[] { android.R.attr.colorAccent });
int color = typedArray.getColor(0, 0);

This works for me. You might be able to replace android.R.attr.colorAccent with your color resource.

Upvotes: 0

dieter_h
dieter_h

Reputation: 2727

Change:

Definition of the style.xml:

<style name="MyTheme.Light" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorAccent">@color/button_color</item>
</style>

Definition of colors.xml:

<color name="button_color">#ff0000</color>  

Source:

getResources().getColor(R.color.button_color);

Upvotes: 3

Related Questions