Search code examples
androidandroid-jetpack-composecard

Set ContentColor for a card depending on the current containerColor


I'm implementing a note card, each card can have different background color and I want the content color to change corresponding to the given background color

Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color(note.color),
            contentColorFor(backgroundColor = Color(note.color))
        )
    ) 

I tried to use the contentColorFor() function but it just gives the default content color.

  • What I want to do is: If the background color is a dark color the corresponding content color should be white If the background color is a light color the corresponding cotent color should be black

Solution

  • You can do something like this with ColorUtils.calculateLuminance(color) < 0.5:

     fun isDark(color: Int): Boolean {
            return ColorUtils.calculateLuminance(color) < 0.5
        }
    
    
        fun getCardContentColor(accentColor: Int): Color {
            val color =
                if (isDark(accentColor)) {
                    Color.White
                } else {
                    Color.DarkGray
                }
            return color
        }
    }