Adjust Tonal Elevation for Material Design 3 Components in Jetpack Compose?
Asked Answered
Q

1

8

Is it possible to adjust the tonalElevation (but not the shadowElevation) of Material Design 3 components?

It looks as though it's only possible to adjust both. Below is the implementation of a Floating Action Button in Material Design 3. The same problem exists with other components.

@Composable
fun FloatingActionButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
    shape: Shape = FabPrimaryTokens.ContainerShape,
    containerColor: Color = FabPrimaryTokens.ContainerColor.toColor(),
    contentColor: Color = contentColorFor(containerColor),
    elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
    content: @Composable () -> Unit,
) {
    Surface(
        onClick = onClick,
        modifier = modifier,
        shape = shape,
        color = containerColor,
        contentColor = contentColor,
        tonalElevation = elevation.tonalElevation(interactionSource = interactionSource).value,
        shadowElevation = elevation.shadowElevation(interactionSource = interactionSource).value,
        interactionSource = interactionSource,
    ) {
        CompositionLocalProvider(LocalContentColor provides contentColor) {
            // Adding the text style from [ExtendedFloatingActionButton] to all FAB variations. In
            // the majority of cases this will have no impact, because icons are expected, but if a
            // developer decides to put some short text to emulate an icon, (like "?") then it will
            // have the correct styling.
            ProvideTextStyle(
                MaterialTheme.typography.fromToken(ExtendedFabPrimaryTokens.LabelTextFont),
            ) {
                Box(
                    modifier = Modifier
                        .defaultMinSize(
                            minWidth = FabPrimaryTokens.ContainerWidth,
                            minHeight = FabPrimaryTokens.ContainerHeight,
                        ),
                    contentAlignment = Alignment.Center,
                ) { content() }
            }
        }
    }
}
Querulous answered 6/4, 2022 at 18:38 Comment(0)
S
8

There's an extension function on a ColorScheme class, that converts an Elevation into a Color: surfaceColorAtElevation().

TextField(
    ...
    colors = TextFieldDefaults.textFieldColors(
        containerColor = MaterialTheme.colorScheme.surfaceColorAtElevation(1.dp)
    )
)

Also, there are six different Elevation levels in Material 3 (https://m3.material.io/styles/elevation/tokens):

Level 0: 0dp
Level 1: 1dp
Level 2: 3dp
Level 3: 6dp
Level 4: 8dp
Level 5: 12dp
Shortie answered 3/11, 2022 at 20:32 Comment(1)
Cannot access 'surfaceColorAtElevation': it is internal in 'androidx.compose.material3'Begun

© 2022 - 2024 — McMap. All rights reserved.