Jetpack Compose with Kotlin: Create a composable function with a textfield for name entry
Video: Jetpack Compose with Kotlin: Create a composable function with a textfield for name entry by Taught by Celeste AI - AI Coding Coach
Watch full page →Jetpack Compose with Kotlin: Create a Composable Function with a TextField for Name Entry
In this example, you'll learn how to create a simple composable function in Jetpack Compose that includes a TextField for users to enter their name. This function manages the input state and displays the entered name dynamically, demonstrating basic state handling and UI updates in Compose.
Code
import androidx.compose.foundation.layout.Column
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.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun NameEntry() {
// Remember the current text input state
val name = remember { mutableStateOf("") }
Column(modifier = Modifier.padding(16.dp)) {
// TextField for user to enter their name
TextField(
value = name.value,
onValueChange = { newValue -> name.value = newValue },
label = { Text("Enter your name") }
)
// Display the entered name below the TextField
if (name.value.isNotEmpty()) {
Text(
text = "Hello, ${name.value}!",
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(top = 8.dp)
)
}
}
}
Key Points
- Use the
rememberfunction withmutableStateOfto hold and update input state in a composable. TextFieldcomposable provides an editable text input with a label and handles user input viaonValueChange.- UI elements automatically recompose and update when the state changes, reflecting user input instantly.
- Use layout composables like
Columnand modifiers such aspaddingto arrange and style UI components.