I am trying to restric the app from affected fro system font scaling. I had gone through many solutions but none helped. Most of them tell use dp instead of sp for text sizes but in compose we can use only sp if i am right as it expects a Text Unit. Is there any right way to restrict font scaling in our app done with jetpack compose ? Please help .
Asked
Active
Viewed 1,662 times
3

howettl
- 12,419
- 13
- 56
- 91

Harish Padmanabh
- 307
- 4
- 17
-
1Might be a duplicate of [https://stackoverflow.com/questions/67918698/why-is-there-only-sp-in-fontsize-of-text-composable-and-not-dp-in-jetp](https://stackoverflow.com/questions/67918698/why-is-there-only-sp-in-fontsize-of-text-composable-and-not-dp-in-jetp) – mlebedy May 18 '22 at 09:34
-
1Have you checked this answer? https://stackoverflow.com/a/69112444/3585796 – Phil Dukhov May 18 '22 at 10:37
3 Answers
5
You can have an extension for Int
or Float
like this
@Composable
fun Int.scaledSp(): TextUnit {
val value: Int = this
return with(LocalDensity.current) {
val fontScale = this.fontScale
val textSize = value / fontScale
textSize.sp
}
You can add an extension parameter of Int
val Int.scaledSp:TextUnit
@Composable get() = scaledSp()
Text(text = "Hello World", fontSize = 20.scaledSp)

Thracian
- 43,021
- 16
- 133
- 222
2
override fun attachBaseContext(newBase: Context?) {
val newOverride = Configuration(newBase?.resources?.configuration)
if (newOverride.fontScale >= 1.1f)
newOverride.fontScale = 1.1f
applyOverrideConfiguration(newOverride)
super.attachBaseContext(newBase)
}
You can use something like this in your main activity.

George
- 21
- 1
0
Till there is no solution on jetpack compose for Text()
, you can use AndroidView:
@Composable
fun CustomText(
// attributes you need to set
){
AndroidView(factory = { context ->
AppCompatTextView(context).apply {
setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25)
setText("")
// other attributes you want to set or other features which is not available in jetpack compose now.
}
},)
}

DeePanShu
- 1,236
- 10
- 23