Text in Jetpack Compose is similar to TextView. The Text composable is used to show labels and paragraphs inside Android apps. This tutorial will show how to implement Text in the app and the available attributes of Text composable. Please check the following example program.
Page Contents
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NewComposeProjectTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Text(text = "Hello World")
}
}
}
}
}
The example program shows the implementation of the Text composable to display Hello World on the screen. It’s time to check out the attributes of Text Composable.
Text Size: –
The fontSize attribute is used to set the size of the text. Please note the fontSize attribute accepts size in TextUnit. So to recast a number into TextUnit use the .sp extension.
Text(
text = "Hello World",
fontSize = 12.sp
)
Text Color: –
The colour of the text can be specified using the colour attribute. This attribute accepts the object of the Color(androidx.compose.ui.graphics.Color) class. We can pass static variables of the Color class like Color.Black. Furthermore, we can also create the object of this class by passing the colour code in the constructor Color(0xFF000000).
Text(
text = "Hello World",
color = Color.Red
)
Text(
text = "Hello World",
color = Color(0xFF00FF00)
)
Font Weight: –
The font weight of the Text Composable can be mentioned using the fontWeight attribute. This attribute accepts the object of the FontWeight class. The FontWeight class has plenty of predefined font weights in the form of static variables.
Text(
text = "Hello World",
fontWeight = FontWeight.SemiBold //another option FontWight(600) or FontWight.W600
)
Static Variable | Thickness |
FontWight.Thin (FontWight.W100) | Thin |
FontWight.ExtraLight (FontWight.W200) | ExtraLight |
FontWight.Light (FontWight.W300) | Light |
FontWight.Normal (FontWight.W400) | Normal |
FontWight.Medium (FontWight.W500) | Medium |
FontWight.SemiBold (FontWight.W600) | SemiBold |
FontWight.Bold (FontWight.W700) | Bold |
FontWight.ExtraBold (FontWight.W800) | ExtraBold |
FontWight.Black (FontWight.W900) | Black |
Italic Text: –
The fontStyle attribute makes text italic Text composable.
Text(
text = "Hello World",
fontStyle = FontStyle.Italic
)
Letter Spacing: –
The space between letters can be updated using the letterSpacing attribute. This attribute accepts TextUnit.
Text(
text = "Hello World",
letterSpacing = 12.sp
)
Woo hoo, we have done with some common characteristics of Text composable. There are numerous other attributes available. We recommend you play with Text Composable and observe what changes all other properties make.