Open In App

How to Set Maximum Input Length in TextField in Android using Jetpack Compose?

Improve
Improve
Like Article
Like
Save
Share
Report

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.

EditText in Android

 

So in this article, we will show you how you could Set Maximum Input Length in TextField in Android using Jetpack Compose. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.geeksforgeeks.jctextfieldmaxlength
  
import android.os.Bundle
import android.widget.Toast
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.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import com.geeksforgeeks.jctextfieldmaxlength.ui.theme.JCTextFieldMaxLengthTheme
  
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // Calling the composable function 
            // to display element and its contents
            MainContent()
        }
    }
}
  
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent() {
    Scaffold(
        topBar = { TopAppBar(title = { Text("GFG | TextField Max Length", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
        content = { MyContent() }
    )
}
  
// Creating a composable function
// to create a TextField
// Calling this function as content
// in the above function
@Composable
fun MyContent(){
  
    // creating a string variable 
    // to store TextField value
    var mText by remember { mutableStateOf(TextFieldValue("")) }
      
    // creating a variable of value 5
    val mMaxLength = 5
  
    // fetching local context
    val mContext = LocalContext.current
  
    Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
            
          // Creating a text field and adding a 
          // condition to limit the input to 5 chars.
          TextField(
            singleLine = true,
            value = mText,
            onValueChange = {
                if (it.text.length <= mMaxLength) mText = it
                else Toast.makeText(mContext, "Cannot be more than 5 Characters", Toast.LENGTH_SHORT).show()
            }
        )
    }
}
  
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MainContent()
}


Output:

You can see that the TextField input is now limited to 5 characters.



Last Updated : 29 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads