androidandroid-jetpack-composeandroid-jetpack-compose-textmaterial-youmaterial-design-3

Unable to change text emphasis using LocalContentAlpha in Material Design 3


Currently, I am migrating one of my apps to Material Design 3 which is entirely written in Kotlin using Jetpack Compose.

While using Material Design 2, I was able to change the emphasis of the text using the code below.

CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
                Text(
                    text = "Hello, world",
                    style = MaterialTheme.typography.h6,
                    fontWeight = FontWeight.SemiBold,
                )
            }

However, the same code doesn't work for Material Design 3 and the text has the default emphasis. Also, I can't find the relevant function anywhere for Material Design 3. I would like to know if there is any official way to achieve the same effect.


Solution

  • The "Emphasis and content alpha" section in the Migrate from Material 2 to Material 3 in Compose details the API changes.

    Material2:

    import androidx.compose.material.ContentAlpha
    import androidx.compose.material.LocalContentAlpha
    
    // High emphasis
    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
        Icon(…)
    }
    // Medium emphasis
    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
        Icon(…)
    }
    // Disabled emphasis
    CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.disabled) {
        Icon(…)
    }
    

    Material3:

    import androidx.compose.material3.LocalContentColor
    
    // High emphasis
    CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) {
        Icon(…)
    }
    // Medium emphasis
    CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurfaceVariant) {
        Icon(…)
    }
    // Disabled emphasis
    CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)) {
        Icon(…)
    }