Home > Software design >  Android - Jetpack compose default background color in non Scaffold Composables
Android - Jetpack compose default background color in non Scaffold Composables

Time:01-10

I am implementing theming using Jetpack compose. I define my theme like below and everything works fine if I use Scaffold as my Composable's parent for each fragment.

CompositionLocalProvider(
    LocalColors provides if (isDarkTheme) {  DarkColorPallet } else {  LightColorPallet }
) {
    MaterialTheme(
        colors = colors(LocalColors.current),
        shapes = Shapes( medium = RoundedCornerShape(16.dp) ),
        content = content
    )
}

But in one fragment I use Box as a parent Composable. In this fragment the background is a color that is not defined in my colors implementation. I don't understand where it comes from and how to override it. It's a dark color when Dark mode is enabled and white when it's not. So it must come from some theming mechanism but which one? I also checked the themes.xml files and there was nothing there either.

CodePudding user response:

For Containers like Box you can give background color using the Modifier.background,

Box(
    Modifier
       .background(Color.Red)
        .fillMaxSize()
    ) {}

CodePudding user response:

If you go to the LightColorPalette variable you will see this:

/* Other default colors to override
background = Color.White,  -> here it says the background color is white in LightColorPalette by default
surface = Color.White,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
*/

if you want to change the background color of the box then you should do either one of these :

Box(
        modifier = Modifier.background(Color.Red) // you can choose other colors as well
   )

But if you want to give a custom color then :

Box(
        modifier = Modifier.background(Color(0xFF338E3A)) // you can pass the hex value inside the color function to get a custom color 
   )
  • Related