'Prevent Text in Jetpack Compose from enlarging when device font size is increases
I have a screen in my app which displays a timer. If the user decides to increase the font size in the device settings menu then the text becomes too large for the layout and it begins to wrap. This is not an issue for my other screens that are more text heavy. For this screen - and only this screen - I would prefer to prevent the timer text from increasing in size if accessibility options are used.
The code in question looks like this, if it adds context:
HorizontalPager(state = pagerState, dragEnabled = dragEnabled) { page ->
val timeInSeconds = abs(steps[page % steps.size] / 1000L)
val minutes = (timeInSeconds / 60).toString().padStart(2, '0')
val seconds = (timeInSeconds % 60).toString().padStart(2, '0')
Text(
modifier = Modifier.fillMaxWidth(0.85f),
text = stringResource(R.string.pomodoro_active_notification_content_body, minutes, seconds),
textAlign = TextAlign.Center,
fontSize = LocalDimens.current.intervalTimeFontSize,
style = MaterialTheme.typography.h1
)
}
Solution 1:[1]
val textStyle = MaterialTheme.typography.h1
val fontSizeDp = with(LocalDensity.current) { textStyle.fontSize.value.dp.toSp() }
Text(
...
style = textStyle,
fontSize = fontSizeDp,
)
Solution 2:[2]
This is an extension function for Int but you can do it for Float if you wish to
@Composable
fun Int.scaledSp(): TextUnit {
val value: Int = this
return with(LocalDensity.current) {
val fontScale = this.fontScale
val textSize = value / fontScale
textSize.sp
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yaroslav Yermolenko |
| Solution 2 | Thracian |



