Developers always prefer to limit the number of characters of input according to the needs. Let’s learn how to limit the maximum characters of TextField in Jetpack Compose.
There is no built-in way to set a maximum number of TextField characters in compose. But you can limit characters by adding a condition inside OnValueChange. See the code snippet given below.
@Composable
fun Example() {
var value by remember { mutableStateOf("") }
val maxLength = 8
TextField(
value = value,
onValueChange = {
if (it.length <= 8)
value = it
},
label = { Text("Enter text") },
modifier = Modifier.padding(20.dp)
)
}
As you see, the maximum length is set as 8. We set the value only if the length is less than or equal to eight.
Following is the complete code.
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Surface(
color = MaterialTheme.colors.background
) {
Example()
}
}
}
}
}
@Composable
fun Example() {
var value by remember { mutableStateOf("") }
val maxLength = 8
TextField(
value = value,
onValueChange = {
if (it.length <= 8)
value = it
},
label = { Text("Enter text") },
modifier = Modifier.padding(20.dp)
)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApplicationTheme {
Example()
}
}
That’s how you set the maximum characters for TextField in Jetpack Compose.