How do select color of contact badge. What algorithm using?
Asked
Active
Viewed 2,952 times
1

vmtrue
- 1,724
- 18
- 36
-
My guess it that it's just randomly chosen. – Jonas Czech Jan 12 '16 at 18:29
-
@JonasCz But after application restart colors will be saved. – vmtrue Jan 12 '16 at 18:32
-
Yes, it saves the randomly generated colors when it first generates them (when the contact is added) – Jonas Czech Jan 12 '16 at 18:33
-
@JonasCz Do you know approach to get color? – vmtrue Jan 12 '16 at 18:35
-
Okay, from the answers I learnt that it is not random, but generated based on the hashcode of the contact name. For generating a random color, try the answer below, or search for "generate random color java". – Jonas Czech Jan 12 '16 at 19:24
2 Answers
7
It does not save. It uses the hashcode of the Contact name string to determine the color.
Example:
String name = "Harish";
int colors[] = new int[] { Color.RED, Color.GREEN, Color.BLUE};
int chosenColor = colors[Math.abs(name.hashCode()) % colors.length];
I learnt from this answer

Community
- 1
- 1

Harish Sridharan
- 1,070
- 6
- 10
1
You can try a Color generator like this..
public class ColorGenerator {
public static ColorGenerator DEFAULT;
public static ColorGenerator MATERIAL;
static {
DEFAULT = create(Arrays.asList(
//your list of default tints
));
MATERIAL = create(Arrays.asList(
//your list of material colors
));
}
private final List<Integer> mColors;
private final Random mRandom;
public static ColorGenerator create(List<Integer> colorList) {
return new ColorGenerator(colorList);
}
private ColorGenerator(List<Integer> colorList) {
mColors = colorList;
mRandom = new Random(System.currentTimeMillis());
}
public int getRandomColor() {
return mColors.get(mRandom.nextInt(mColors.size()));
}
public int getColor(Object key) {
return mColors.get(Math.abs(key.hashCode()) % mColors.size());
}
}

Suraj Kumar Sau
- 438
- 6
- 10