So in the current andriod development, if we need to reference to a color set in the theme, we could simply do: (in layout xml)
....
<TextView
...
android:textColor="?attr/colorPrimary"
.../>
....
If I set a color blue in the theme. I will get that color in the textview above.
I was wondering how I could do the same in Jetpack Compose
. In Compose
, we do,
MaterialTheme(...) {
Column {
Text(
...
textStyle = TextStyle(color = ????) // How to I reference to the theme?
)
}
}
A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.
If you want to change the state of TextField and also update the UI, you can use a MutableState . Compose observes any reads and writes to the MutableState object and triggers a recomposition to update the UI.
You can use something like:
Text(text = "....",
style = TextStyle(color = MaterialTheme.colors.primary))
Compose provide ColorPalette
based on Material color specification to generate you app theme. It provide lightColorPalette
and darkColorPalette
for defining theme for light and dark mode respectively.
val lightThemeColors = lightColorPalette(
primary = Color(0xFFFFFFFF),
primaryVariant = Color(0xFFFFFFFF),
onPrimary = Color.Black,
secondary = Color.Transparent,
onSecondary = Color.White,
background = Color.White,
onBackground = Color(0xFF212121),
surface = Color.White,
onSurface = Color(0xFF212121),
error = Color.Red,
onError = Color.White
)
val darkThemeColors = darkColorPalette(
primary = Color(0xFF000000),
primaryVariant = Color(0xFF000000),
onPrimary = Color.White,
secondary = Color.White,
onSecondary = Color.White,
surface = Color(0xFF212121),
background = Color(0xFF212121),
onBackground = Color.White,
onSurface = Color.White,
error = Color.Red,
onError = Color.White
)
MaterialTheme(
colors = if(isSystemInDarkTheme()) darkThemeColors else lightThemeColors
) {
Column {
Text(
textStyle = TextStyle(color = MaterialTheme.colors.primary)
)
}
}
If you want to add more custom color to you theme you can use ColorPalette
with extension variable like shown below
@Composable
val ColorPalette.myColor: Color
get() = if(!isLight) Color(0xFF424242) else Color.White
Now you can use MaterialTheme.colors.myColor
to include.
If you want to include color from android colors xml you can do that using colorResource(id = R.color.anyName)
function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With