Issue
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:
- Import the xml file from the link to my project under
res
folder (ex.res/values/android_material_design_colours.xml
) Get all colors from the file
int[] allColors =
(missing part)Get the random color by using
Random
classint randomColor = allColors[new Random().nextInt(allColors.length)];
Is this possible or are there any better way? Please Help.
Solution
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;
}
Answered By - yesterdaysfoe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.