Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Taking Input in Android using Jetpack Compose
Next article icon

Taking Input in Android using Jetpack Compose

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

EditText is one of the most important widgets which is seen in most of the apps. This widget is generally used to get the data from users. Users can directly communicate with the app using this widget. This widget is used to get the data from the user in the form of numbers, text or any other text. In this article, we will take a look at the implementation of the TextField composable function in Android using Jetpack Compose. 

Important Attributes of TextField Widget

Attributes 

Description

value value is used to get the entered value from the user in the text field.
placeholder

if the text field is empty we are displaying a hint to the user what he 

has to enter in the text field. 

keyboardOptions

keyboardOptions is used to add capitalization in the data which is entered by the user in the text field, we can also specify an auto correction option in this. We can specify the type of keyboard which we have to display such as (phone, text) and to display actions which can be performed from the keyboard itself. 

textStyleto add styling to the text entered by the user. It is used to add font family, font size and styling to our text. 
maxLinesto add maximum lines for our text input field. 
focusedTextColor

active color is used when a user has clicked on edit text or the text field is focused and entering some data in the text field. 

singleLineIn this, we have to specify a boolean value to avoid moving user input into multiple lines. 
disabledTextColorInactive color is specified when the user is not being focused on our Text Input Field. 
colorsto specify the background color for our text input field.
leadingIcon

This method is used to add the leading icon to our text input field. With this method, we can also specify the color(tint) for our icon.

trailingIcon

This method is use to add trailing icon to our text input field. With this method we can also specify color(tint) for our icon.

minLines

Used to set the minimum number of lines.

shape

Used to provide the shape to the TextField which is set to the medium shape from the theme.

enabled

used to make the TextField is enabled, allowing user interaction.

readOnly

used to make the TextField not read-only, allowing text input.

label

a composable used for displaying a label for the TextField.

isError

used to show the TextField is not in an error state.

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 EditText 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.

text-compose-dir


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

MainActivity.kt:

MainAcitivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import androidx.activity.* import androidx.activity.compose.setContent import androidx.compose.foundation.layout.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.*  class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         setContent {             MaterialTheme {                 Surface(color = MaterialTheme.colorScheme.background) {                     MyTextFieldUI()                 }             }         }     } }  @Composable fun MyTextFieldUI() {     // Remember the text entered in the TextField     var text by remember { mutableStateOf("") }      // Layout to organize the TextField and the Text below it     Column(         modifier = Modifier             .fillMaxSize()             .padding(16.dp),         verticalArrangement = Arrangement.Center,         horizontalAlignment = Alignment.CenterHorizontally     ) {         // TextField for user input         TextField(             value = text,             onValueChange = { text = it },             label = { Text("Enter your text") },             modifier = Modifier.fillMaxWidth()         )          Spacer(modifier = Modifier.height(16.dp))          // Displaying the text entered by the user         Text(text = "You entered: $text")     } }  @Preview(showBackground = true) @Composable fun PreviewMyTextFieldUI() {     MyTextFieldUI() } 

Output:

Example of the TextField in Android Jetpack Compose

In this example we are adding some extra functionality to the TextField.

MainActivity.kt:

MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import androidx.activity.* import androidx.activity.compose.setContent import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.* import androidx.compose.ui.text.input.* import androidx.compose.ui.text.style.* import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.* import org.geeksforgeeks.demo.ui.theme.DemoTheme  class MainActivity : ComponentActivity() {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         setContent {             DemoTheme {                 Surface(color = MaterialTheme.colorScheme.background) {                     MyTextFieldUI()                 }             }         }     } }  @Composable fun MyTextFieldUI() {     // we are creating a variable for     // getting a value of our text field.     val inputValue = remember { mutableStateOf(TextFieldValue()) }      Column(         // we are using column to align our         // textField to center of the screen.         modifier = Modifier             .fillMaxWidth()             .fillMaxHeight(),          // below line is used for specifying         // vertical arrangement.         verticalArrangement = Arrangement.Center,          // below line is used for specifying         // horizontal arrangement.         horizontalAlignment = Alignment.CenterHorizontally,     ) {         TextField(             // below line is used to get             // value of text field,             value = inputValue.value,              // below line is used to get value in text field             // on value change in text field.             onValueChange = { inputValue.value = it },              // modifier is used to add padding             // to our text field.             modifier = Modifier                 .padding(all = 16.dp)                 .fillMaxWidth(),              // below line is used to specify TextField is enabled, allowing user interaction.             enabled = true,              // below line is used to specify TextField is not read-only, allowing text input.             readOnly = false,              // below line is used to specify             // styling for our text field value.             textStyle = TextStyle(                 color = Color.Black,                  // below line is used to add font                 // size for our text field                 fontSize = 15.sp,                 fontWeight = FontWeight.SemiBold,                 fontStyle = FontStyle.Normal,                  // below line is used to change font family.                 fontFamily = FontFamily.SansSerif,                 letterSpacing = 0.5.sp,                 textDecoration = TextDecoration.None,                 textAlign = TextAlign.Start             ),             //  A composable displaying a label for the TextField.             label = { Text("Label") },              // below line is used to add placeholder             // for our text field.             placeholder = { Text("Enter user name") },              // leading icon is used to add icon             // at the start of text field.             leadingIcon = {                 // In this method we are specifying                 // our leading icon and its color.                 Icon(Icons.Filled.AccountCircle, contentDescription = null, tint = Color(0xFF6200EE))             },             // trailing icons is used to add             // icon to the end of text field.             trailingIcon = {                 Icon(Icons.Filled.Info, contentDescription = null, tint = Color(0xFF6200EE))             },             // below line is used to indicate the TextField is not in an error state.             isError = false,              // below line is used to indicate no visual transformation is applied to the text.             visualTransformation = VisualTransformation.None,              // keyboard options is used to modify             // the keyboard for text field.             keyboardOptions = KeyboardOptions(                 // below line is used for capitalization                 // inside our text field.                 capitalization = KeyboardCapitalization.None,                  // below line is used to enable auto                 // correct in our keyboard.                 autoCorrect = true,                  // below line is used to specify our                 // type of keyboard such as text, number, phone.                 keyboardType = KeyboardType.Text,                 imeAction = ImeAction.Done             ),             keyboardActions = KeyboardActions(                 onDone = {                     // Handle the done action                 }             ),             // single line boolean is used to avoid             // text field entering in multiple lines.             singleLine = true,              // below line is used to give             // max lines for our text field.             maxLines = 2,              // below line is used to give             // max lines for our text field.             minLines = 1,              //  below line uses a MutableInteractionSource for handling interaction states.             interactionSource = remember { MutableInteractionSource() },              // below line is used for the shape of the TextField is set to the medium shape from the theme.             shape = MaterialTheme.shapes.medium,              // below line is used to specify background             // color for our text field.             colors = TextFieldDefaults.colors(                 focusedTextColor = Color.Green,                 disabledTextColor = Color.Green,                 focusedContainerColor = Color.LightGray,                 unfocusedContainerColor = Color.LightGray,                 cursorColor = Color.Blue,                 errorCursorColor = Color.Red,                 focusedIndicatorColor = Color.Transparent,                 unfocusedIndicatorColor = Color.Transparent             )         )          Spacer(modifier = Modifier.height(16.dp))          // Displaying the text entered by the user         Text(text = "You entered: ${inputValue.value.text}")     } }  // @Preview function is used to see preview // for our composable function in preview section @Preview(showBackground = true) @Composable fun DefaultPreview() {     DemoTheme {         MyTextFieldUI()     } } 

Output: 


Next Article
Taking Input in Android using Jetpack Compose

C

chaitanyamunje
Improve
Article Tags :
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Android-Jetpack

Similar Reads

    Text in Android using Jetpack Compose
    Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. Android Text 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 Text in Android using Jetpack Compose. Importan
    5 min read
    SmsManager in Android using Jetpack Compose
    Many times while building an android application we have to add a feature through which users will be able to directly send SMS from our android application. So in this article, we will take a look at How to send a text message over a phone using SMS Manager in Android using Jetpack Compose. A sampl
    6 min read
    ListView in Android using Jetpack Compose
    A ListView is a UI component that displays data in a vertically scrollable list, where each item is placed one below the other. It is widely used in Android applications to showcase categorized data in an organized manner. In Jetpack Compose, the traditional ListView from XML-based layouts is replac
    2 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 compo
    3 min read
    Date Picker in Android using Jetpack Compose
    In Android, a Date Picker is a widget used to select a date from the calendar. When a Date Picker is implemented in an application, the user can select a year, a month, and a day, combining to form date from a calendar-like-looking box. This data is generally needed and collected in applications tha
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences