android - Retrieve color programmatically from R.color -


I have a ListView that contains many text visuals, and in a text view, the color of a different background, depending on the data should be there.

Because I do not want to hardcode the colors to set my colors, so I r. It works fine, but I have to manually check for every color, because I'm aware that someone is able to get the color like a hashmap. So my first attempt was:

  switch (line) {case "1": linecolor = context.getResources (). GetColor (R.color.line1); Case "2": line color = context.gate resources (). GetColor (R.color.line2); .... ....}  

It is far from clear code, so I tried a different approach using string-array:

  & lt; String-array name = "line_glo_name" & gt; & Lt; Items & gt; 1 & lt; / Item & gt; & Lt; Items & gt; 2 & lt; / Item & gt; .... & lt; / String-arrays & gt; & Lt; String-array name = "line_glo_value" & gt; & Lt; Items & gt; # E00023 & lt; / Item & gt; & Lt; Items & gt; # Ef9ec1 & lt; / Item & gt; .... & lt; / String-arrays & gt;  

In my adapter class I have just created a hashmap and put this string-array together:

  string [] line_color_names = context.getResources (). GetStringArray (R.array.line_color_names); String [] line_color_values ​​= context.getResources (). GetStringArray (R.array.line_color_values); LineColors = New Hashmap & lt; String, string & gt; (); {LineColors.put (line_color_names [i], line_color_values ​​[i]) for (int i = 0; i & lt; line_color_names.length; i ++); }  

So my question is whether it is to achieve only one method or is there any other, ideally R. By taking color directly from the color?

Thank you!

You can get color ID using the resource name ( R.color.foo ) and solve it at runtime:

  public int getColorIdByResourceName (string name) {int color; {Class res = R.color.class; Field field = res.getField (name); Int color = field.getInt (empty); } Hold (exception e) {e.printStackTrace (); } The color of the return; }  

and then

  int colorId = getColorIdByResourceName ("foo21"); Int colorVal = getResources (). GetColor (getColorIdByResourceName ("foo21"));  

Comments