I want the size of the text to be in .dp
so that it doesn't change according to the system font.
How to achieve this in Jetpack Compose "Text" composable
Asked
Active
Viewed 5,859 times
14

Abhimanyu
- 11,351
- 7
- 51
- 121

Rishad Baniya
- 665
- 8
- 14
-
1`so that it doesnt change according to the system font. ` doesn't sound very user friendly. what if i can't read your font size ? – a_local_nobody Jun 10 '21 at 09:50
-
2The `fontSize` works with a `TextUnit`. It can accept `sp` and `em` – Gabriele Mariotti Jun 10 '21 at 09:52
-
1I just wanted to keep a consistent font size for my bottom navigation bar labels. Just used ```em``` and it worked. – Rishad Baniya Jun 10 '21 at 09:54
2 Answers
21
The Compose team does not intend to provide that possibility, em
are a bit pita to use, but there is an easy workaround should anyone really need it.
@Composable
fun dpToSp(dp: Dp) = with(LocalDensity.current) { dp.toSp() }
Text("ABCD", fontSize = dpToSp(15.dp))
Taken from the same issue tracker: https://issuetracker.google.com/190644747.

Michał Klimczak
- 12,674
- 8
- 66
- 99
-
3I was the one who asked that on issue tracker but forgot to update that answer here in stackoverflow; thank you for providing the code :D – Rishad Baniya Jun 15 '21 at 16:19
-
it is not easy to handle the interface when the user increases or decreases the font size. So this option is also somewhat reasonable. Thank you! – Đốc.tc May 10 '23 at 02:22
3
You can use extension properties:
private fun Int.textDp(density: Density): TextUnit = with(density) {
this@textDp.dp.toSp()
}
val Int.textDp: TextUnit
@Composable get() = this.textDp(density = LocalDensity.current)

yong wei
- 125
- 1
- 2