Vivek Modi
Vivek Modi

Reputation: 7211

Use of letter spacing in jetpack compose

I want to use letterSpacing in my Text(). I did it like this

letterSpacing = 0.7.sp

but when I move this value to dimen.xml and using like this

letterSpacing = dimensionResource(id = R.dimen.text_letter_spacing),

It giving me error on Text().

Error

None of the following functions can be called with the arguments supplied.
Text(AnnotatedString, Modifier = ..., Color = ..., TextUnit = ..., FontStyle? = ..., FontWeight? = ..., FontFamily? = ..., TextUnit = ..., TextDecoration? = ..., TextAlign? = ..., TextUnit = ..., TextOverflow = ..., Boolean = ..., Int = ..., Map<String, InlineTextContent> = ..., (TextLayoutResult) → Unit = ..., TextStyle = ...) defined in androidx.compose.material
Text(String, Modifier = ..., Color = ..., TextUnit = ..., FontStyle? = ..., FontWeight? = ..., FontFamily? = ..., TextUnit = ..., TextDecoration? = ..., TextAlign? = ..., TextUnit = ..., TextOverflow = ..., Boolean = ..., Int = ..., (TextLayoutResult) → Unit = ..., TextStyle = ...) defined in androidx.compose.material

Image on Error

enter image description here

Upvotes: 3

Views: 3851

Answers (3)

canerkaseler
canerkaseler

Reputation: 7508

If you need use negative letter spacing also you can use this in jetpack compose:

letterSpacing = TextUnit(-0.36F, TextUnitType.Sp),

Upvotes: 0

Vivek Modi
Vivek Modi

Reputation: 7211

Thanks @Thracian for guidance.

Option 1

I solve the problem by converting to toSp() because dimensionResource returns a value in dp but letterSpacing expects TextUnit.

val letterSpacing = with(LocalDensity.current) {
    dimensionResource(R.dimen.text_letter_spacing).toSp()
}
Text( 
    .... // more attribute here
    letterSpacing = letterSpacing,
)

Option 2

Thanks @RobertJamison for suggestions to use TextUnit directly.

Text(
    .... // more attribute here
    letterSpacing = TextUnit(0.7F, TextUnitType.Sp) ,
)

we can directly use TextUnit in letterSpacing. Be careful that TextUnit is ExperimentalUnitApi.

@OptIn(ExperimentalUnitApi::class)

we have to add in function of the class.

Upvotes: 6

Robert Jamison
Robert Jamison

Reputation: 299

When you move resource values to dimen.xml, it doesn't retain the unit of measure. You should try actually setting a TextUnit value.

Upvotes: 0

Related Questions