Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert TextUnit to Dp in Jetpack Compose?

I know the difference between them. I want to calculate the text height base on lineHeight. The value of lineHeight is in TextUnit so I want to convert it into Dp.

like image 519
Agna JirKon Rx Avatar asked Jan 25 '21 23:01

Agna JirKon Rx


People also ask

What is mutableStateOf in jetpack compose?

mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. interface MutableState<T> : State<T> { override var value: T } Any changes to value will schedule recomposition of any composable functions that read value .

What is LazyColumn in jetpack compose?

A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.

Is jetpack compose declarative?

Jetpack Compose is a modern declarative UI Toolkit for Android. Compose makes it easier to write and maintain your app UI by providing a declarative API that allows you to render your app UI without imperatively mutating frontend views.


2 Answers

You need to grab the current Density from the LocalDensity—so this will only work in composition, within a @Composable function—and use that to convert to Dp:

val lineHeightSp: TextUnit = 12.sp
val lineHeightDp: Dp = with(LocalDensity.current) {
     lineHeightSp.toDp()
}
like image 77
Ryan M Avatar answered Oct 16 '22 16:10

Ryan M


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

val Int.textDp: TextUnit
    @Composable get() =  this.textDp(density = LocalDensity.current)
like image 42
yong wei Avatar answered Oct 16 '22 16:10

yong wei