https://kotlinlang.org logo
#compose
Title
# compose
h

Horv

07/28/2020, 2:31 PM
Just getting into Compose, struggling a bit with styling and themes. What's the best practice way to set text color? I'd imagined Text-komponent would pick some color from my Theme's colors but that doesn't seem to be the case?
Heh, when I set color in my
typography
initially it just showed up as black. But must have had some incorrect hexvalue there. Switching to
Color.White
worked. Isn't font-color decided by theme?
v

Vinay Gaba

07/28/2020, 3:59 PM
Can you post code the snippet that you used?
p

pavi2410

07/28/2020, 7:55 PM
Same thing that I have observed too.
Copy code
MaterialTheme {
  Column {
    repeat(10) {
      Text(text = it.toString())
    }
  }
}
Source: https://www.github.com/pavi2410/jetpack_compose_test/tree/master/app%2Fsrc%2Fmain%2Fjava%2Fcom%2Fexample%2Fjetpackcomposetest%2FMyScreen.kt I thought that Material theme should switch the Text's font color when dark mode is on. But no, it didn't inherit the font color from the theme. I tried to backtrace the font color property only to find that it is set to use Color.Black as the default color. I couldn't find anything in the source that tells it to use the color supplied by the theme (I may be wrong here, but that's what I have found). This was long before so I couldn't remember to file it a bug or confirm it here. I am sharing screenshots showing this behavior with dark mode on and off.
v

Vinay Gaba

07/28/2020, 8:06 PM
In one of the earlier versions of Compose, the Text composable was using the Theme value as the default value. This seem to have changed now. In order for Text to inherit the color of the theme, you will have to use one of the Theme colors explicitly
MaterialTheme.colors.onSurface
Here’s a more complete example: https://github.com/vinaygaba/Learn-Jetpack-Compose-By-Example/blob/master/app/src/main/java/com/example/jetpackcompose/theme/DarkModeActivity.kt#L292
n

nickbutcher

07/29/2020, 8:17 AM
Text
uses
contentColor()
by default (unless a
TextStyle
or the
Text
component specify a color). Something needs to set content color for this to work correctly. In Material all content lives on a notional "surface" which is modeled by the
Surface
composable, which you commonly use to set background colors, elevation etc. Doing this also sets a contrasting content color (under the hood it does this using the
ContentColorAmbient
which
contentColor()
retrieves ). If nothing sets a content color then the default value is black.
tl;dr; Add a
Surface
between
MaterialTheme
and your
Column
and this will work as expected
💡 1
👍 2
v

Vinay Gaba

07/29/2020, 4:31 PM
Great tip!
2 Views