How to format TextField in Jetpack Compose

What is TextField?

TextField allows users to enter and modify text. This page describes how you can implement TextField, style TextField input, and configure other TextField options, like keyboard options and visually transforming user input.

Note: if you want more customization over the TextFiled you can use BasicTextField for that customization.

Difference between EditText And TextField are you have to manage the state for showing the changes in TextField?

Best practices with state

  • Use MutableState to represent TextField state: Avoid using reactive streams like StateFlow to represent TextField state, as these structures might introduce asynchronous delays.
  • Avoid delays to update the state: When you call onValueChange, update your TextField synchronously and immediately.
  • Where to define the state: If your TextField the state requires business logic validations as you type, it is correct to hoist the state to your ViewModel. If it doesn’t, you can use composable or a state-holder class as the source of truth. To learn more about where to hoist your state, see the state hoisting documentation.

Format TextField (Avoiding Cyclic Recomposition)

import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.withStyle


@Composable
fun StyleEditTextWithoutInfiniteRecomposition() {
    val testText = remember { mutableStateOf(TextFieldValue()) }
    TextField(
        value = testText.value,
        onValueChange = {
            testText.value = it
        },
        visualTransformation = {
            TransformedText(
                text = buildAnnotatedString {
                    withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
                        append(testText.value.text)
                    }
                },
                offsetMapping = OffsetMapping.Identity
            )
        }
    )
}

This is how you can change TextField Style without cyclic recomposition.

Conclusion

We have not directly edited the value rather we have changed the style using visualTransformation so that we don’t force Jetpack to re-compose it again and again.

Hope you enjoy coding Jetpack Compose 😁. Don’t forget to share 📨 and clap 👏. Follow me on LinkedIn and Twitter For More Updates 🔔

Happy Compose !! 🚀

Leave a Comment