The Jetpack Compose Text widget represents the fundamental building block for displaying text content in Compose-based Android applications. Unlike the traditional TextView in the View system, the Jetpack Compose Text widget embraces a declarative approach, making text rendering more intuitive and powerful for Android developers.
@Composable
fun BasicText() {
Text(text = "Hello, Jetpack Compose Text Widget!")
}
The Jetpack Compose Text widget operates as a composable function, enabling seamless integration within your Compose hierarchy. This widget handles text rendering with impressive efficiency, automatically managing recomposition when its parameters change while maintaining optimal performance through Compose's smart recomposition system.
The Jetpack Compose Text widget offers extensive customization through various parameters that control its appearance and behavior. Let's explore these essential properties:
The most basic property of the Jetpack Compose Text widget is the text
parameter, which accepts both simple strings and annotated strings:
@Composable
fun TextContentExamples() {
Column {
// Simple string text
Text(text = "Regular Jetpack Compose Text")
// Using string resources
Text(text = stringResource(R.string.jetpack_compose_text_example))
// Using AnnotatedString for rich text
Text(
text = buildAnnotatedString {
append("Jetpack ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("Compose ")
}
withStyle(style = SpanStyle(fontStyle = FontStyle.Italic, color = Color.Blue)) {
append("Text Widget")
}
}
)
}
}
The Jetpack Compose Text widget seamlessly integrates with Android's localization system through the stringResource
function, ensuring your application maintains proper internationalization practices while leveraging the modern Compose UI toolkit.
The Jetpack Compose Text widget embraces Material Design principles through an extensive typography system:
@Composable
fun TextTypographyExamples() {
Column {
Text(
text = "Headline Large Text with Jetpack Compose",
style = MaterialTheme.typography.headlineLarge
)
Text(
text = "Body Medium Text with Jetpack Compose",
style = MaterialTheme.typography.bodyMedium
)
Text(
text = "Label Small Text with Jetpack Compose",
style = MaterialTheme.typography.labelSmall
)
}
}
The style
parameter in the Jetpack Compose Text widget accepts TextStyle objects, allowing comprehensive control over typography. You can use predefined styles from MaterialTheme.typography or create custom TextStyle instances to achieve unique text presentations in your Compose applications.
The Jetpack Compose Text widget provides granular control over font properties:
@Composable
fun TextFontExamples() {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "Custom Font Size in Jetpack Compose Text",
fontSize = 20.sp
)
Text(
text = "Bold Text in Jetpack Compose",
fontWeight = FontWeight.Bold
)
Text(
text = "Italic Text in Jetpack Compose",
fontStyle = FontStyle.Italic
)
Text(
text = "Custom Font Family in Jetpack Compose Text",
fontFamily = FontFamily.Monospace
)
// Using custom fonts
val customFont = FontFamily(
Font(R.font.roboto_regular),
Font(R.font.roboto_bold, FontWeight.Bold)
)
Text(
text = "Custom Font Family with Weights in Jetpack Compose",
fontFamily = customFont,
fontWeight = FontWeight.Bold
)
}
}
The Jetpack Compose Text widget supports custom font families through the FontFamily class, enabling Android developers to incorporate brand-specific typography into their Compose applications while maintaining a modern, declarative approach to UI development.
The Jetpack Compose Text widget offers comprehensive layout control to ensure your text appears exactly as intended:
@Composable
fun TextAlignmentExamples() {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
text = "This Jetpack Compose Text is aligned to start",
textAlign = TextAlign.Start,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "This Jetpack Compose Text is center aligned",
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "This Jetpack Compose Text is aligned to end",
textAlign = TextAlign.End,
modifier = Modifier.fillMaxWidth()
)
Text(
text = "This Jetpack Compose Text demonstrates justification with longer content that spans multiple lines within the container",
textAlign = TextAlign.Justify,
modifier = Modifier.fillMaxWidth()
)
}
}
The textAlign
parameter in the Jetpack Compose Text widget determines how text aligns within its allocated width. For proper alignment control, ensure the Text widget has a defined width, typically achieved by applying Modifier.fillMaxWidth()
or a specific width constraint.
The Jetpack Compose Text widget provides sophisticated controls for handling text that exceeds available space:
@Composable
fun TextOverflowExamples() {
Column(
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.padding(16.dp)
) {
Text(
text = "This is a very long text in Jetpack Compose that demonstrates overflow handling with ellipsis at the end when the content doesn't fit in a single line",
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = "This Jetpack Compose Text demonstrates clipping overflow behavior when text doesn't fit in the allocated space",
maxLines = 1,
overflow = TextOverflow.Clip
)
Text(
text = "This Jetpack Compose Text has exactly 2 lines maximum with ellipsis overflow handling. It contains enough text to demonstrate how the content gets truncated with an ellipsis when it exceeds the allocated space for two lines in the layout.",
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Text(
text = "This Jetpack Compose Text has soft line wrapping enabled with specific line height",
lineHeight = 24.sp
)
}
}
The combination of maxLines
and overflow
parameters in the Jetpack Compose Text widget gives Android developers precise control over how text behaves when space is limited, ensuring optimal reading experiences even in constrained UI environments.
Fine typography control in the Jetpack Compose Text widget extends to spacing between letters and words:
@Composable
fun TextSpacingExamples() {
Column(
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.padding(16.dp)
) {
Text(
text = "Jetpack Compose Text with increased letter spacing",
letterSpacing = 2.sp
)
Text(
text = "Jetpack Compose Text with custom word spacing",
style = TextStyle(
wordSpacing = 8.sp
)
)
}
}
These spacing controls in the Jetpack Compose Text widget allow Android developers to achieve precise typographic layouts that enhance readability and visual appeal in modern mobile applications.
The Jetpack Compose Text widget extends beyond basic text display with several advanced capabilities:
The Jetpack Compose framework provides the ClickableText composable for handling tap interactions:
@Composable
fun ClickableTextExample() {
val annotatedText = buildAnnotatedString {
append("By using the ")
// First clickable part
pushStringAnnotation(tag = "URL", annotation = "https://developer.android.com/jetpack/compose")
withStyle(style = SpanStyle(color = Color.Blue, textDecoration = TextDecoration.Underline)) {
append("Jetpack Compose Text widget")
}
pop()
append(" you can create ")
// Second clickable part
pushStringAnnotation(tag = "ACTION", annotation = "OPEN_SETTINGS")
withStyle(style = SpanStyle(color = Color.Green, textDecoration = TextDecoration.Underline)) {
append("interactive text")
}
pop()
append(" in your Android application.")
}
ClickableText(
text = annotatedText,
onClick = { offset ->
annotatedText.getStringAnnotations(tag = "URL", start = offset, end = offset)
.firstOrNull()?.let { annotation ->
// Handle URL click
Log.d("ClickableText", "URL clicked: ${annotation.item}")
}
annotatedText.getStringAnnotations(tag = "ACTION", start = offset, end = offset)
.firstOrNull()?.let { annotation ->
// Handle action click
Log.d("ClickableText", "Action clicked: ${annotation.item}")
}
}
)
}
The ClickableText composable enables Android developers to implement in-text links and interactive sections, enhancing the user experience with contextual actions directly within text content.
Jetpack Compose provides the SelectionContainer for enabling text selection:
@Composable
fun SelectableTextExample() {
SelectionContainer {
Text(
text = "This Jetpack Compose Text is selectable. Users can highlight and copy this content.",
style = MaterialTheme.typography.bodyLarge
)
}
}
The SelectionContainer in Jetpack Compose enables users to select and copy text, enhancing accessibility and user experience in information-rich applications.
The Jetpack Compose Text widget supports inline content through InlineTextContent:
@Composable
fun TextWithInlineContent() {
val myText = buildAnnotatedString {
append("Jetpack Compose Text with ")
appendInlineContent(id = "inlineIcon")
append(" inline content")
}
val inlineContent = mapOf(
"inlineIcon" to InlineTextContent(
Placeholder(
width = 20.sp,
height = 20.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.TextCenter
)
) {
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = "Heart Icon",
tint = Color.Red
)
}
)
Text(
text = myText,
inlineContent = inlineContent
)
}
This feature allows Android developers to embed composables directly within text flows, creating rich, interactive text experiences that seamlessly combine text and graphical elements.
The Jetpack Compose Text widget prioritizes accessibility through several key features:
@Composable
fun AccessibleTextExample() {
Text(
text = "Accessible Jetpack Compose Text Example",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier
.semantics {
contentDescription = "Headline describing Jetpack Compose Text accessibility"
heading() // Marks this as a heading for screen readers
}
)
Text(
text = "This Jetpack Compose Text demonstrates semantic properties for enhanced accessibility in Android applications",
fontSize = 18.sp,
lineHeight = 24.sp // Improved readability with generous line height
)
}
Additional accessibility considerations for the Jetpack Compose Text widget include:
Sufficient Color Contrast: Ensure text colors have adequate contrast against their backgrounds for readability.
Scalable Text: Use sp (scale-independent pixels) units for text sizes to respect system font size settings.
Meaningful Content Descriptions: Provide content descriptions for decorative text or text with special meaning.
Support for Screen Readers: Test your Jetpack Compose Text implementations with TalkBack to verify proper screen reader functionality.