Sort things by colors in Android

Anthony Stéphan
2 min readJun 27, 2018

--

Tast the rainbow!

Sometimes it’s nice to sort UI elements by color.

Since colors are defined by integers in Android, the first idea is to sort according the color value.

Bad idea, this would not do anything good!

The HSL representation

Most of time, we are using the RGB representation (Red-Green-Blue) when we work with colors.

But sometimes it’s a good alternative to work with the HSL projection: Hue-Saturation-Lightness.

Properly sort your colors

First step, get the HSL representation of your color:

fun Int.getHSL(): FloatArray {
val hsl = FloatArray(3)
ColorUtils.colorToHSL(this, hsl)
for (i in 0 until hsl.size) {
hsl[i] = hsl[i] * 100
}
return hsl
}

Note that hue, saturation and lightness are Float values between 0 and 1. We multiply then by 100 to work with percentages instead, and it will be easier to handle the value comparisons in our comparator:

fun sortColorList(randomColors: IntArray) {
randomColors.sortedWith(Comparator { o1, o2 ->
val
hsl1 = o1.getHSL()
val hsl2 = o2.getHSL()

// Colors have the same Hue
if (hsl1[0] == hsl2[0]) {

// Colors have the same saturation
if (hsl1[1] == hsl2[1]) {
// Compare lightness
(hsl1[2] - hsl2[2]).toInt()

} else {
(hsl1[1] - hsl2[1]).toInt()
}

} else {
(hsl1[0] - hsl2[0]).toInt()
}
})
}
See the result in a RecyclerView with a GridLayoutManager

--

--

Anthony Stéphan

Senior Android Developer (Freelance), funder of AS Mobile Development and developer of Printoid for OctoPrint (on Google Play)