androidandroid-layoutandroid-jetpack-composeandroid-jetpack-compose-textandroid-compose-textfield

How to override the text color in TextField in Jetpack Compose using MaterialTheme?


I'm trying to use TextField() from Jetpack Compose. I want the text color to be white.

I found this to be working:

ProvideTextStyle(TextStyle(color = Color.White)) {
   TextField(
       ...
   )
}

However, I want to override this in the Theme level, so that I don't need to repeatedly write ProvideTextStyle. I saw that MaterialTheme only accepts the following params:

@Composable
fun MaterialTheme(
    colors: Colors = MaterialTheme.colors,
    typography: Typography = MaterialTheme.typography,
    shapes: Shapes = MaterialTheme.shapes,
    content: @Composable () -> Unit
)

So I'm not sure how to do it. Can someone help?

(compose version = 1.0.0-alpha11)


Solution

  • I want to override this in the Theme level

    Modify the content of MaterialTheme composable in your app's theme composable to include TextStyle.

    @Composable
    fun MyAppTheme(
        darkTheme: Boolean = isSystemInDarkTheme(),
        content: @Composable() () -> Unit
    ) {
        val colors = if (darkTheme) {
            DarkColorPalette
        } else {
            LightColorPalette
        }
    
        MaterialTheme(
            colors = colors,
            typography = Typography,
            shapes = Shapes,
            content = {
                ProvideTextStyle(
                    value = TextStyle(color = Color.White),
                    content = content
                )
            }
        )
    }
    

    Now your provided TextStyle will be used at App theme level.

    setContent {
        MyAppTheme {
            // app content
        }
    }