Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the font size of a text when I use Text() in Compose?

I create a new project by Empty Compose Activity wizard in Android Studio.

The Code A is generated code by Android Studio.

Text(text = "Hello $name!") displays a text with default font style, I hope to get the size and unit of the text, such as 16sp, where can I find these informations?

Code A

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {               
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Greeting("Android")
                }
            }
        }
    }
}

@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}

@Composable
fun MyApplicationTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) {
        DarkColorPalette
    } else {
        LightColorPalette
    }

    MaterialTheme(
        colors = colors,
        typography = Typography,
        shapes = Shapes,
        content = content
    )
}
like image 336
HelloCW Avatar asked Sep 11 '25 06:09

HelloCW


1 Answers

You can check it here.
https://developer.android.com/jetpack/compose/text

Change text size and font style

Text("Hello World", fontSize = 30.sp,fontStyle = FontStyle.Italic)

Text has a fontFamily parameter to allow setting the font used in the composable. By default, serif, sans-serif, monospace and cursive font families are included.

You can use the TextLayoutResult to get the front style
The font style is in TextLayoutInput -> TextStyle

Text("Hello World", 
        onTextLayout = { result: TextLayoutResult ->
             Log.d(TAG, "FrontSize: "+ result.layoutInput.style.fontSize)
             Log.d(TAG, "FrontStyle: "+ result.layoutInput.style.toString())
    })
like image 89
Desmond Avatar answered Sep 14 '25 15:09

Desmond