Unable to change text emphasis using LocalContentAlpha in Material Design 3

3.1k views Asked by At

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.

2

There are 2 answers

0
Chris Lacy On BEST ANSWER

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(…)
}
0
Phil Dukhov On

MaterialTheme.typography.h6 is from Material 2, which means you're using Text composable from Material 2 too.

Material 3 analog of h6 is MaterialTheme.typography.headlineSmall.

Make sure you have correct imports of both Text and MaterialTheme - these should be imported from androidx.compose.material3 package. Also make sure you provide a correctly imported theme, e.g. here.

Wrong imports is the most common mistake when migrating to M3, so be patient with it.

Also note that LocalContentAlpha doesn't exists in M3, providing M2 version will have no effect on M3 views. You can compare how Text composable determines its color in M2 and in M3.

I'm not sure wether it's gonna be added later (it's alpha after all), or it's handled in some other way in M3, here's a workaround(which is not perfect for sure):

CompositionLocalProvider(LocalContentColor provides LocalContentColor.current.copy(alpha = 0.4f)) {

p.s. LocalContentColor needs to be imported from M3 too