0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Use Text in Compose in Android: Simple Guide

In Android Jetpack Compose, use the Text composable to display text on the screen. Simply call Text("Your text here") inside a composable function to show text in your UI.
๐Ÿ“

Syntax

The Text composable displays a string of text on the screen. You provide the text as a string parameter. You can also customize its appearance using optional parameters like color, fontSize, and fontWeight.

Basic syntax:

  • Text(text = "Hello World") - shows simple text.
  • color - sets text color.
  • fontSize - sets size of the text.
  • fontWeight - sets thickness of the font.
kotlin
Text(text = "Hello World")
Output
Displays the text "Hello World" on the screen
๐Ÿ’ป

Example

This example shows a complete composable function that displays a greeting message with customized font size and color.

kotlin
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp

@Composable
fun Greeting() {
  Text(
    text = "Welcome to Compose!",
    color = Color.Blue,
    fontSize = 24.sp,
    fontWeight = FontWeight.Bold
  )
}
Output
Text "Welcome to Compose!" shown in blue, bold, and large font size
โš ๏ธ

Common Pitfalls

Beginners often forget to mark their functions with @Composable, which is required to use Text inside Compose UI. Another mistake is passing null or empty strings, which results in no visible text. Also, avoid using raw pixel sizes; use sp units for font size to support different screen densities.

kotlin
/* Wrong: Missing @Composable annotation */
fun ShowText() {
  Text("Hello")
}

/* Right: With @Composable annotation */
@Composable
fun ShowText() {
  Text("Hello")
}
๐Ÿ“Š

Quick Reference

Remember these tips when using Text in Compose:

  • Always use @Composable annotation on functions using Text.
  • Use sp units for font sizes.
  • Customize text appearance with parameters like color, fontSize, and fontWeight.
  • Use string resources for localization instead of hardcoded strings.
โœ…

Key Takeaways

Use the Text composable to display text in Jetpack Compose UI.
Always mark your UI functions with @Composable to use Text.
Customize text appearance with parameters like color and fontSize.
Use sp units for font sizes to support different screen densities.
Avoid empty or null strings to ensure text is visible.