2. Text in Compose
🎯 Goal : In this article, we will explore how to use Text in Jetpack Compose, covering basic usage, styling, fonts, and text customization. By the end, you’ll be able to create beautifully styled and responsive text for your Compose-based UI.
Basic Text() Usage
The simplest way to display text in Compose:
@Composable
fun BasicTextExample() {
Text("Hello, Jetpack Compose!")
}
📝 By default, the text uses the system’s default styling.
💞I write these articles to help fellow developers. If you found this useful and want to support my work, you can do so here: Buy Me a Coffee ☕
Styling Text (Font Size, Color, Font Style)
@Composable
fun StyledTextExample() {
Text(
text = "Styled Text",
fontSize = 24.sp, // Font size
fontWeight = FontWeight.Bold, // Bold text
fontStyle = FontStyle.Italic, // Italic text
color = Color.Blue // Change text color
)
}
🔎fontWeight: controls how thick or bold the text appears
🔎fontStyle: controls whether the text is normal or italic
Custom Fonts
Use fontFamily to apply custom fonts.
val customFont = FontFamily(
Font(R.font.lobster_regular, FontWeight.Normal)
)
@Composable
fun CustomFontExample() {
Text(
text = "Custom Font",
fontFamily = customFont,
fontSize = 20.sp
)
}
📌 Make sure the font file is in res/font and added to fonts.xml.
⚠️ File-based resource names must contain only lowercase a-z, 0–9, or underscore.
Text Overflow Handling
When text is too long, use maxLines and overflow.
@Composable
fun OverflowTextExample() {
Text(
text = "This is a long text that may not fit in one line.",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
📝 Adds … when the text is too long to fit in one line.
Clickable Text
Make text interactive using Modifier.clickable.
@Composable
fun ClickableTextExample() {
Text(
text = "Click Me",
color = Color.Blue,
modifier = Modifier.clickable { println("Text Clicked!") }
)
}
Annotated Text (Multiple Styles in One Text)
Use AnnotatedString to apply different styles in a single Text().
@Composable
fun AnnotatedTextExample() {
Text(
buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Red, fontSize = 18.sp)) {
append("Hello, ")
}
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("Compose!")
}
}
)
}
📝 Combines red-colored normal text with bold text in one line.
Text with Background and Padding
@Composable
fun PaddedTextExample() {
Text(
text = "Padded Text",
modifier = Modifier
.background(Color.Gray)
.padding(16.dp)
)
}