The Wayback Machine - https://web.archive.org/web/20240822200812/https://www.geeksforgeeks.org/textview-in-android-using-jetpack-compose/
Open In App

TextView in Android using Jetpack Compose

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. Android TextView is a simple view in Android which is used to display text inside our App.

In this article, we will take a look at the implementation of TextView in Android using Jetpack Compose. 

Attributes of TextView

Attributes

Description

textto set the text which we have to display inside our TextView.
style to change the style of Text in Android.
colorto change the color of TextView.
fontSizeto change the font size of our text. 
fontWeight to set the weight for our font ie. to extra bold, dark, and many more
fontStyleto set font style to italic.
fontFamilyto change the font family of our text.
letterSpacingto set spacing in between letters of our TextView.  
backgroundto set the background color for our TextView. 
shadowto add a shadow for our TextView.  
textAlignto change the alignment of our TextView.
modifierthe modifier is used to add padding to our TextView. 

textDecoration

the decoration to be applied to the text

lineHeight

the height of each line of text.

overflow

how to handle overflowed text

softWrap

whether to wrap the text if it exceeds the width of its container.

maxLines

the maximum number of lines for the text

minLines

the minimum number of lines for the text.

onTextLayout

callback that is invoked when the text is laid out.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.

Step 2: Adding Text in MainActivity.kt file

Navigate to the app > java > your app’s package name and open the MainActivity.kt file. Inside that file add the below code to it.

Directory_Structure


Comments are added inside the code to understand the code in more detail.

MainActivity.kt
package com.gfg.textview_jetpack_compose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.gfg.textview_jetpack_compose.ui.theme.TextView_Jetpack_ComposeTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TextView_Jetpack_ComposeTheme {
                Surface(color = MaterialTheme.colorScheme.background) {
                    MyTextView("Geeks for Geeks")
                }
            }
        }
    }
}

@Composable
fun MyTextView(data1: String, modifier: Modifier = Modifier) {
    Column(
        // we are using column to align
        // our textview to center of the screen.
        modifier = Modifier.fillMaxSize(),

        // below line is used for specifying
        // horizontal arrangement.
        horizontalAlignment = Alignment.CenterHorizontally,

        // below line is used for specifying
        // vertical arrangement.
        verticalArrangement = Arrangement.Center
    ){
        Text(text ="$data1", modifier = modifier)
    }
}

Output Screenshot of the Application:

TextView



Example of the TextView in Android Jetpack Compose

In this example we are adding some extra functionality to the TextView:

MainActivity.kt
package com.gfg.textview_jetpack_compose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.gfg.textview_jetpack_compose.ui.theme.TextView_Jetpack_ComposeTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TextView_Jetpack_ComposeTheme {
                // A surface container using the
                // 'background' color from the theme
                Surface(
                    // to add background color for our screen.
                    color = MaterialTheme.colorScheme.background,
                ) {
                    // here we are calling our Composable
                    // function inside setContent method.
                    TextExample()
                }
            }
        }
    }
}

// below is the Composable function
// which we have created for our Text.
@Composable
fun TextExample() {
    Column(
        // we are using column to align
        // our textview to center of the screen.
        modifier = Modifier.fillMaxSize(),

        // below line is used for specifying
        // horizontal arrangement.
        horizontalAlignment = Alignment.CenterHorizontally,

        // below line is used for specifying
        // vertical arrangement.
        verticalArrangement = Arrangement.Center
    ) {
        // Text Composable
        Text(
            // below line is for displaying
            // text in our text.
            text = "GeeksforGeeks",

            // modifier is use to give
            // padding to our text.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),

            // color is used to provide white
            // color to our text.
            color = Color.White,

            // font size to change the
            // size of our text.
            fontSize = 40.sp,

            // font style is use to change style
            // of our text to italic and normal.
            fontStyle = FontStyle.Italic,

            // font weight to bold such as light bold,
            // extra bold to our text.
            fontWeight = FontWeight.Bold,

            // font family is use to change
            // our font family to SansSerif.
            fontFamily = FontFamily.SansSerif,

            // letter spacing is use to
            // provide between letters.
            letterSpacing = 1.5.sp,

            // Decorations applied to the text (Underline)
            textDecoration = TextDecoration.Underline,

            // textAlign to align our text view
            // to center position.
            textAlign = TextAlign.Center,

            // The height of each line of text (24sp).
            lineHeight = 24.sp,

            // Used to handle overflowed text (Ellipsis).
            overflow = TextOverflow.Ellipsis,

            // Whether the text should wrap if it exceeds the width of its container (true).
            softWrap = true,

            // The maximum number of lines for the text (2).
            maxLines = 2,

            // The minimum number of lines for the text (1).
            minLines = 1,

            // A callback that is invoked when the text is laid out, here used to print the line count.
            onTextLayout = { textLayoutResult: TextLayoutResult ->
                // Example usage of onTextLayout callback
                val lineCount = textLayoutResult.lineCount
                println("Line Count: $lineCount")
            },

            // below line is used to add
            // style to our text view.
            style = TextStyle(

                // background is use to specify background
                // color to our text view.
                background = Color.Green,

                // shadow to make our
                // text view elevated.
                shadow = Shadow(color = Color.Gray, blurRadius = 40f)
            )
        )
    }
}

@Preview
@Composable
fun DefaultPreview() {
    MaterialTheme {
        // we are passing our composable
        // function to display its preview.
        TextExample()
    }
}

Output: 

Text

Text Output




Similar Reads

Android Jetpack Compose - Interoperability Using Compose in XML Layouts
Writing UI in jetpack compose can be fun, but can be difficult to migrate your whole project into Compose at one time. Fortunately, Jetpack Compose provides Interoperability api to use compose in existing XML views so that you can migrate to compose slowly. Prerequisites: Knowledge of Jetpack Compose.Knowledge of KotlinKnowledge of Android’s View.
3 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. In this article, we will show you how you could start a New Activity using Intent in Android using Jetpack Compose. Follow
4 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose. Note: If you are
9 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose. Note: If you
9 min read
Horizontal ListView in Android using Jetpack Compose
Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only avai
6 min read
Material Design Text Input Field using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
3 min read
How to Remove TextField Padding in Android using Jetpack Compose?
In Android Jetpack Compose, a TextField is used to take input from the user in the form of text. TextField when in focus or when clicked invokes a soft keyboard. In general, TextField is highly attributed for a better feel and appearance. However, we can use a pre-developed TextField, named BasicTextField, which has no attributes like that of a reg
3 min read
WebView in Android using Jetpack Compose
In Android, a WebView is an extension of View Class that allows us to display webpages. In simpler words, if you want to display a webpage in Activity Layout, then you can implement a WebView to display it. It is very similar to a browser but isn't one. A WebView can rather be referred to as a show or a preview of a browser as it lacks most functio
3 min read
Play Audio in Android using Jetpack Compose
In Android, a MediaPlayer is used to play media files like audio and video files in the application. The MediaPlayer Class uses the MediaPlayer API for performing various functions like creating a MediaPlayer, playing, pausing, starting, and stopping the media. In this article, we will show you how you could play an Audio File on Android using Jetp
3 min read
Curved Text in Android using Jetpack Compose
In Android, there are no inbuilt schemes to implement designed text like the word art, which is available in applications like MS Word. We can always refer to or download such schemes like designed font faces to implement designed text. However, it is also possible to natively build (building from scratch) such designed texts in an Android Project.
3 min read
How to Get Screen Width and Height in Android using Jetpack Compose?
Android applications are being developed for different device orientations to support a huge range of devices. So that users with different device size configurations can use the application. Many applications need to get the height and width of the device screen to create UI. In this article, we will take a look at How to get Screen Width and Heig
5 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is used which is used to read pdf and get the data from
6 min read
TopAppBar in Android using Jetpack Compose
TopAppBar is similar to that of the Action Bar widget in Android. This is one of the most UI components in Android. The action bar is used to represent the app name and action items in Android. In this article, we will take a look at the implementation of the TopAppBar in Android using Jetpack compose. Attributes of Top App Bar WidgetAttributes Des
3 min read
How to Draw Track on Google Maps in Android using Jetpack Compose?
In many android apps, we have seen that there is a route marker from a source location to the destination location. In this article, we will take a look at How we can draw a track on Google Maps in Android using Jetpack Compose. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo create a new project in Android Studio please
6 min read
Material Design Buttons using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
4 min read
Snackbar in Android using Jetpack Compose
Prerequisites: Snackbar Material Design Components in AndroidJetpack Compose in Android Snackbar is a lightweight widget and they are used to show messages at the bottom of the application. It was introduced with the Material Design library as a replacement for a Toast. In this article, we will explain how you can create a Snackbar using Jetpack Co
2 min read
Custom Chips using Jetpack Compose in Android
Chips in android are one of the components which are used to make the choice filters, actions, and display the selectable options in the compact area of the Android Window. In this article, we will use Android's Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build. Note that we are going
5 min read
How to make Text Selectable in Android using Jetpack Compose?
By default, Composable Texts are not selectable which means users cannot copy text from your application, and to enable text selection you need to wrap the text elements into Selection Container. In this article, we will use Android’s Jetpack Compose to create those chips. A sample image is given below to give an idea of what we are going to build.
2 min read
How to Create a Timer using Jetpack Compose in Android?
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. In this article, we are going to create a Timer using Jetpack Compose. Below is the sample video to show what we are going to build. [video mp4="https://m
4 min read
ConstraintLayout in Android using Jetpack Compose
ConstraintLayout is the view system in a ViewGroup to place widgets relative to the position of other widgets on the screen. In jetpack compose, almost every layout can be created using Rows and Columns but if you want to create larger complicated Layouts you can also use Constraint Layout as an alternative to Rows and Columns. In this article, we
5 min read
How to Create Superscript and Subscript Text using Jetpack Compose in Android?
In this article, we will explain how to create a Superscript and Subscript text using Jetpack Compose. Below is the sample picture to show what we are going to build. Note that we are going to implement this project using the Kotlin language. Prerequisites: Basic Knowledge of Kotlin.Jetpack Compose in Android.Step by Step Implementation Step 1: Cre
2 min read
Scaffold in Android using Jetpack Compose
There are a lot of apps that contain TopAppBar, Drawer, Floating Action Button, BottomAppBar (in the form of bottom navigation), Snackbar. While you can individually set up all of these in an app but takes a lot of setups. Jetpack Compose provides Scaffold Composable which can save a lot of time. It's like a prebuilt template. In this article, we w
6 min read
Animated Splash Screen in Android Using Jetpack Compose
Jetpack Compose is Android's advanced toolkit for creating materialistic UI in a very simpler form. It does not require any kind of XML files in Android Studio also it helps to create native applications as well. It is recently launched in the Android Studio Arctic Fox version. Jetpack Compose Functions are declared as: @Composable fun MessageCard(
4 min read
Building UI Using Jetpack Compose in Android
Jetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the
11 min read
Drop-Down Menu in Android using Jetpack Compose
In Android, a TextField is used to take text-based input from the user to perform a particular task. This text can be general text or be specific to characters, numbers, etc. However, this is not the only purpose of implementing a TextField. A TextField can also be converted into a drop-down menu displaying options to be selected by the user. So in
3 min read
Add Hyperlink at a Particular Text Span in Android using Jetpack Compose
In Android, a TextView is used to display text inside the activity on the screen. Similarly, in Jetpack Compose, a Text element is used to display text on the activity screen. By default, Text cannot create a hyperlink around the text, So, we create a hyperlink using Annonated String and display it using Clickable Text. So in this article, we will
3 min read
Implement IME Action Buttons in Soft Keyboard in Android using Jetpack Compose
In Android, IME (Input Method Action) Action Button is a key on the Soft Keyboard that represents different actions that can be displayed. In the below image, we have located the IME Action Buttons of two different types. In the below image, you can see the different types of actions that can be displayed in the IME Action Button on the Soft Keyboa
3 min read
How to Validate TextFields in a Login Form in Android using Jetpack Compose?
In Android, TextField validation means checking if the user inputs are sufficient for a task to start or call a function. Generally, validation takes place in forms where the user is required to give mandatory inputs (fields marked with an asterisk). The most common examples of such forms are registration or sign-up forms and login forms. In this a
3 min read
three90RightbarBannerImg