2

I find this list of material design color and I want to get random color from it. I am new in android development and don't fully understand how android resources works.

I know that I can get the custom color by R.color.my_color from res/values/colors.xml but I want to separate my app custom colors from material design colors.

What I'm trying to do:

  1. Import the xml file from the link to my project under res folder (ex. res/values/android_material_design_colours.xml)
  2. Get all colors from the file

    int[] allColors = (missing part)

  3. Get the random color by using Random class

    int randomColor = allColors[new Random().nextInt(allColors.length)];

Is this possible or are there any better way? Please Help.

yesterdaysfoe
  • 768
  • 3
  • 7
  • 23
  • 1
    Look here: http://stackoverflow.com/questions/5347107/creating-integer-array-of-resource-ids Instead of drawable use color. I hope everything will be clear. The idea is just the same – krossovochkin Oct 13 '15 at 11:24
  • 1
    Is this the last way? I mean, I'm looking for a simple way that I don't have to alter the file and not to copy and paste one by one. – yesterdaysfoe Oct 13 '15 at 11:37

2 Answers2

4

Because I'm avoiding to alter the file, I do it by reading the xml. Good thing Android has class android.content.res.XmlResourceParser that simplify xml parsing. I end up with this solution:

Imported the xml file to my project under res/xml folder (ex. res/xml/android_material_design_colours.xml)

List<Integer> allColors = getAllMaterialColors();
int randomIndex = new Random().nextInt(allColors.size());
int randomColor = allColors.get(randomIndex);

and

private List<Integer> getAllMaterialColors() throws IOException, XmlPullParserException {
    XmlResourceParser xrp = getContext().getResources().getXml(R.xml.materialcolor);
    List<Integer> allColors = new ArrayList<>();
    int nextEvent;
    while ((nextEvent = xrp.next()) != XmlResourceParser.END_DOCUMENT) {
        String s = xrp.getName();
        if ("color".equals(s)) {
            String color = xrp.nextText();
            allColors.add(Color.parseColor(color));
        }
    }
    return allColors;
}
yesterdaysfoe
  • 768
  • 3
  • 7
  • 23
2

Create string-array with all material colors.

<resources>
    <string-array name="colors">        
        <item>#ff0000</item>
        <item>#00ff00</item>  
        <item>#0000ff</item>
    </string-array>
</resources>

Get colors array in the activity

String[] allColors = context.getResources().getStringArray(R.array.colors);

Parse string value to get int value:

int randomColor = Color.parseColor(allColors[new Random().nextInt(allColors.length)]);
HellCat2405
  • 752
  • 7
  • 16