https://kotlinlang.org logo
#android
Title
# android
c

Chetan Tuteja

07/28/2022, 8:38 AM
Hey guys! Does anyone know if we have a replacement for the
ems
property in Jetpack Compose?
m

Mert TUTSAK

07/28/2022, 8:58 AM
did you use
letterSpacing
property in TextStyle ?
c

Chetan Tuteja

07/28/2022, 9:03 AM
I haven't tried that. I'll check it out, but, I think letter spacing is a different property from ems because back in XML both were available.
android:ems
or
setEms(n)
sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. Letter spacing is not the same I would say.
c

Chrimaeon

07/28/2022, 9:15 AM
there is
androidx.compose.ui.unit.TextUnitKt#getEm(int)
. You can use the same way as
dp
->
24.em
c

Chetan Tuteja

07/28/2022, 9:17 AM
@Chrimaeon Could you give an example? Back in XML EMS was a separate property from text size? Like I could set text size to be 16sp and ems to be 11 or 12 or whatever. What would be the equivalent in compose to achieve the same?
c

Chrimaeon

07/28/2022, 9:18 AM
in compose you set it on the Text composable:
Copy code
Text(
  text = ""Text,
  fontSize = 24.em
)
Ah, now I get it what you mean - you set both in XML!? but I guess if you combined them in XML one value would overrule the other 🤔
c

Chetan Tuteja

07/28/2022, 9:25 AM
I'm working rn in Compose, but, I am saying in XML I had them has two different properties. TextSize set the font size basically and the
ems
property allowed be to basically set the ems (or how many characters can be there in one line in a nutshell) I'm looking to achieve the same via Compose now.
c

Chrimaeon

07/28/2022, 9:28 AM
ah
/**
* Sets the width of the TextView to be exactly {@code ems} wide.
*
* This value is used for width calculation if LayoutParams does not force TextView to have an
* exact width. Setting this value overrides previous minimum/maximum configurations such as
* {@link #setMinEms(int)} or {@link #setMaxEms(int)}.
*
* @param ems the exact width of the TextView in terms of ems
*
* @see #setWidth(int)
*
* @attr ref android.R.styleable#TextView_ems
*/
@android.view.RemotableViewMethod
public void *setEms*(int ems)
you might be able to “hack” it like this:
Copy code
Text(
    modifier = Modifier.width(Dp(24.em.value)),
    text = "Text",
)
c

Chetan Tuteja

07/28/2022, 9:31 AM
This looks promising. Let me try. Thanks @Chrimaeon
👍 1
c

Chrimaeon

07/28/2022, 9:34 AM
actually to get the density specific value you’ll need to calculate them first
Copy code
val width = with(LocalDensity.current) {
    24.em.toDp()
}
Text(
    modifier = Modifier.width(width),
    text = "",
)
c

Chetan Tuteja

07/28/2022, 9:38 AM
Looks like something Google's compose team should add by default. I'll try and let you know. Thank you so much!
58 Views