Skip to content

Instantly share code, notes, and snippets.

@KryptKode
Created June 25, 2020 23:08
Show Gist options
  • Save KryptKode/1c31874a77fd5fe252f3c0dd2253ee95 to your computer and use it in GitHub Desktop.
Save KryptKode/1c31874a77fd5fe252f3c0dd2253ee95 to your computer and use it in GitHub Desktop.
<color name="color1">#F57C00</color>
<color name="color2">#EF5350</color>
<color name="color3">#689F38</color>
<color name="color4">#F7B500</color>
<color name="color5">#FF44D0</color>
<color name="color6">#1976D2</color>
import android.content.Context
import androidx.core.content.ContextCompat
class RandomColorHelper(context: Context) {
private val allColors: List<Int> = listOf(
ContextCompat.getColor(context, R.color.color1),
ContextCompat.getColor(context, R.color.color2),
ContextCompat.getColor(context, R.color.color3),
ContextCompat.getColor(context, R.color.color4),
ContextCompat.getColor(context, R.color.color5),
ContextCompat.getColor(context, R.color.color6)
)
fun getRandomColor(position: Int): Int {
val resolvedPosition = position % 6
return allColors[resolvedPosition]
}
fun getRandomColorForInitials(string: String): Int {
val firstLetter = string.first().toString()
return when {
firstLetter.contains(Regex("[A-D]")) -> {
allColors[0]
}
firstLetter.contains(Regex("[E-H]")) -> {
allColors[1]
}
firstLetter.contains(Regex("[I-O]")) -> {
allColors[2]
}
firstLetter.contains(Regex("[P-T]")) -> {
allColors[3]
}
firstLetter.contains(Regex("[U-W]")) -> {
allColors[4]
}
else -> {
allColors[5]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment