Phil Wright Phil Wright - 2 months ago 16
Android Question

How to programmtically 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?

Answer Source

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:

But for a complete reference you have to use the Android source for the API the you are looking at:

So the colors that are defined in the Oreo beta:

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....)