简体   繁体   中英

Prevent system font scaling - Jetpack Compose

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 dp 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.

(Solutions refered): https://l.workplace.com/l.php?u=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F21546805%2Fhow-to-prevent-system-font-size-changing-effects-to-android-application&h=AT0zIuBPbUONm0T6q8PtqbxCdX6P_ywlp-yFGrqPMqZt7H3wsWYltKO5XwbW3i0lenrxxLi3nn_kMO4aPtFUfig2iG0BcRZpd0wTuZ1_XFpdsjDM6E7RPyZ-G_c2dlmuzGqsSEHYbqBJun0hLLZgOpRUszKbe9-1xQ

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
  }

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.
                    }
                },)

}

This way can be succeed.

@Composable
fun DisableFontScale(content: @Composable () -> Unit) {
    val density = LocalDensity.current.density
    CompositionLocalProvider(
        LocalDensity provides Density(
            density = density,
            fontScale = 1f
        ),
        content = content
    )
}

@Composable
fun EnableFontScale(content: @Composable () -> Unit) {
    val density = LocalDensity.current.density
    val fontScale = LocalContext.current.resources.configuration.fontScale
    CompositionLocalProvider(
        LocalDensity provides Density(
            density = density,
            fontScale = fontScale
        ),
        content = content
    )
}

@Composable
fun Example() {
    Column {
        Text(text = "This will be scaled.")
        DisableFontScale {
            Text(text = "This will not be scaled.")
            EnableFontScale {
                Text(text = "We enable font scale, so this will be scaled.")
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM