[go: up one dir, main page]

Open In App

Taking Input in Android using Jetpack Compose

Last Updated : 24 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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.

Directory_Structure


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

MainAcitivity.kt
package com.gfg.edittext_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.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.gfg.edittext_jetpack_compose.ui.theme.EditText_Jetpack_ComposeTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EditText_Jetpack_ComposeTheme {
                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 of the Application:

EditText_Android

Example of the TextField in Android Jetpack Compose

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

MainActivity.kt
package com.gfg.edittext_gfg_jetpack

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.gfg.edittext_gfg_jetpack.ui.theme.EditText_GFG_JetpackTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            EditText_GFG_JetpackTheme {
                // A surface container using the 
                // 'background' color from the theme
                Surface(color = MaterialTheme.colorScheme.background) {
                    // at below line we are calling
                    // our function for text field.
                    TextFieldExample()
                }
            }
        }
    }
}


@Composable
fun TextFieldExample() {
    // 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
            )
        )
    }
}

// @Preview function is used to see preview
// for our composable function in preview section
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    EditText_GFG_JetpackTheme {
        TextFieldExample()
    }
}

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
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 Set Maximum Input Length in TextField in Android using Jetpack Compose?
In Android, EditText is used to collect text-based user input inside the activity on the screen. Similarly, in Jetpack Compose, a TextField element is used to collect input text on the activity screen. By default, there is no limit to what users can type inside the TextField. So in this article, we will show you how you could Set Maximum Input Leng
3 min read
Add an Input Filter to the TextField in Android using Jetpack Compose
In Jetpack Compose, a TextField is a UI element that lets users type in text as an input. This input can then be stored and used for various desired functions. As TextField has no character restrictions, users can type in any character. However, there can be a system where the application would accept only certain characters as input. In such a cas
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
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
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
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
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
How to Disable Text Selection 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, the text displayed in the Text element cannot be selected. To do so, the Text element has to be declared inside a SelectionContainer to make the text selectable.
3 min read
three90RightbarBannerImg