TextView in Jetpack Compose

TextView in Jetpack Compose: A Complete Guide

Jetpack Compose revolutionizes Android UI development by simplifying the creation of UI components using declarative syntax. The Text component in Jetpack Compose, which effectively replaces the traditional TextView in XML-based layouts, is at the core of UI development. This article provides a complete overview of how to work with Text in Jetpack Compose, covering essential properties, styling, interactivity, and advanced features.


What is Text in Jetpack Compose?

In Jetpack Compose, Text is a composable function that serves the same purpose as TextView in the XML layout system, allowing developers to display text on the screen. However, with Text, we can define and style text directly within a composable function, eliminating the need for XML layouts and making code more readable and modular.

@Composable
fun SimpleTextExample() {
    Text(text = "Hello, Jetpack Compose!")
}

Basic Properties of Text in Jetpack Compose

The Text composable offers several properties to control the appearance and behavior of text. Let’s explore some common properties:

  1. text: The content to display. This can be a simple string or a complex text built using AnnotatedString.
  2. color: Sets the color of the text. Color can be customized from Compose’s built-in color palette.
  3. fontSize: Controls the size of the font. It can be set using TextUnit.
  4. fontWeight: Sets the weight of the font (e.g., FontWeight.Bold, FontWeight.Light).
  5. textAlign: Aligns text within the component (e.g., TextAlign.Center, TextAlign.Start).
  6. fontFamily: Customizes the font family used for the text. Compose provides several built-in font families.

Here’s a basic example with these properties in action:

@Composable
fun StyledTextExample() {
    Text(
        text = "Styled Text in Jetpack Compose",
        color = Color.Blue,
        fontSize = 20.sp,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.Center,
        fontFamily = FontFamily.Serif
    )
}

Adding Text Style with TextStyle

TextStyle provides a more modular way to set text properties like color, font, and alignment. Using TextStyle allows for cleaner code, especially when styling is reused.

@Composable
fun TextWithStyle() {
    Text(
        text = "Using TextStyle for Styling",
        style = TextStyle(
            color = Color.Green,
            fontSize = 18.sp,
            fontWeight = FontWeight.Medium,
            letterSpacing = 2.sp,
            fontFamily = FontFamily.SansSerif
        )
    )
}

Customizing Font and Typography

Jetpack Compose allows using custom fonts and typography. Fonts can be imported into the project, declared in the resource directory, and used in FontFamily.

val customFontFamily = FontFamily(
    Font(R.font.my_custom_font, FontWeight.Normal)
)

@Composable
fun CustomFontText() {
    Text(
        text = "Text with Custom Font",
        fontFamily = customFontFamily,
        fontSize = 16.sp
    )
}

You can define typography styles in a Typography object, which helps in setting up consistent styling throughout the app.

val customTypography = Typography(
    body1 = TextStyle(
        fontFamily = customFontFamily,
        fontWeight = FontWeight.Normal,
        fontSize = 16.sp
    )
)

@Composable
fun TypographyText() {
    Text(
        text = "Using Custom Typography",
        style = customTypography.body1
    )
}

Text Alignment and Wrapping

In Compose, text can be aligned within its container using the textAlign property, and multi-line text wrapping can be controlled with maxLines and overflow.

  • maxLines: Restricts the number of lines for the text.
  • overflow: Manages overflow behavior with values like TextOverflow.Ellipsis.
@Composable
fun TextAlignmentExample() {
    Text(
        text = "This is a long text that might exceed the container width",
        maxLines = 1,
        overflow = TextOverflow.Ellipsis,
        textAlign = TextAlign.Center
    )
}

Text Decoration (Underline, Strikethrough)

Text decoration such as underline and strikethrough can be added with the textDecoration property.

@Composable
fun DecoratedText() {
    Text(
        text = "Underlined and Strikethrough Text",
        textDecoration = TextDecoration.combine(
            listOf(TextDecoration.Underline, TextDecoration.LineThrough)
        )
    )
}

Interactive Text with Clickable

Adding clickable actions to text is straightforward in Compose using the Modifier.clickable modifier. This feature makes it easier to implement interactive text, such as hyperlinks or buttons.

@Composable
fun ClickableTextExample() {
    Text(
        text = "Click Me",
        modifier = Modifier.clickable {
            // Action on click
        },
        color = Color.Blue
    )
}

Rich Text with AnnotatedString

For texts with multiple styles (e.g., bold, colored, or underlined sections within the same text), AnnotatedString provides a flexible approach to style parts of the text individually.

@Composable
fun AnnotatedTextExample() {
    val annotatedText = buildAnnotatedString {
        append("Normal Text, ")
        withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
            append("Bold and Red Text")
        }
        append(", Normal Text Again")
    }

    Text(text = annotatedText)
}

Text Shadows

Adding shadows to text enhances its visibility and design. Shadows are added with the shadow property.

@Composable
fun ShadowText() {
    Text(
        text = "Text with Shadow",
        style = TextStyle(
            shadow = Shadow(
                color = Color.Gray,
                offset = Offset(2f, 2f),
                blurRadius = 4f
            )
        )
    )
}

Dynamic Text with State

Jetpack Compose’s declarative model makes it easy to update text based on user actions or data changes. With the State API, text content can dynamically respond to changes.

@Composable
fun DynamicText() {
    var text by remember { mutableStateOf("Initial Text") }

    Column {
        Text(text = text)
        Button(onClick = { text = "Text Updated!" }) {
            Text("Update Text")
        }
    }
}

Text with Background

In Jetpack Compose, adding a background to text is as simple as wrapping the Text composable in a Modifier.background modifier.

@Composable
fun BackgroundText() {
    Text(
        text = "Text with Background",
        modifier = Modifier
            .background(Color.LightGray)
            .padding(8.dp),
        color = Color.Black
    )
}

Responsive Text with autoSizeText

Although Compose does not directly support automatic text resizing, you can use constraints and measurements to create a responsive text layout.

@Composable
fun ResponsiveText() {
    Box(modifier = Modifier.fillMaxWidth()) {
        Text(
            text = "Responsive Text",
            fontSize = 20.sp,
            modifier = Modifier.wrapContentSize()
        )
    }
}

Conclusion

The Text composable in Jetpack Compose offers a powerful, flexible way to work with text in Android applications. Whether you need simple text display, rich formatting, or dynamic text updates, Text in Compose provides all the tools necessary to create engaging and interactive text elements.

Understanding and using the diverse features of Text in Jetpack Compose is essential for building modern, responsive, and visually appealing Android UIs. With Jetpack Compose’s declarative approach, developers can create more maintainable code and enhance user experiences with ease.

Leave a Comment

Your email address will not be published. Required fields are marked *