Why is there only ".sp" in fontSize of Text("") composable and not ".dp" in Jetpack Compose-beta08
Asked Answered
P

3

19

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

Petitionary answered 10/6, 2021 at 9:45 Comment(3)
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 ?Aliquot
The fontSize works with a TextUnit. It can accept sp and emMalaguena
I just wanted to keep a consistent font size for my bottom navigation bar labels. Just used em and it worked.Petitionary
C
27

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.

Comparable answered 15/6, 2021 at 13:46 Comment(2)
I was the one who asked that on issue tracker but forgot to update that answer here in stackoverflow; thank you for providing the code :DPetitionary
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!Nasal
C
4

You can use extension properties:

private fun Int.textDp(density: Density): TextUnit = with(density) {
    [email protected]()
}


val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)
Chifforobe answered 31/7, 2021 at 15:45 Comment(0)
B
0
@Stable
val Int.tdp: TextUnit @Composable get() = textDp()

@Stable
val Double.tdp: TextUnit @Composable get() = textDp()

@Composable
private fun Int.textDp() = with(LocalDensity.current) { [email protected]() }

@Composable
private fun Double.textDp() = with(LocalDensity.current) { [email protected]() }

Use:

Text(
        text = "My Text",
        fontSize = 22.tdp,
        color = Color.White
    )
Breeching answered 23/3 at 16:27 Comment(1)
Welcome on StackOverflow. Can you edit your answer to add details and explain how it works and why it fix the issue from OP?Nevsa

© 2022 - 2024 — McMap. All rights reserved.