import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
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.platform.LocalContext
import androidx.compose.ui.unit.dp
@Composable
fun NameInputScreen() {
val context = LocalContext.current
val nameState = remember { mutableStateOf("") }
Column(modifier = Modifier.padding(16.dp)) {
NameInput(
name = nameState.value,
onNameChange = { newName -> nameState.value = newName },
onSubmit = {
Toast.makeText(context, "Hello, ${nameState.value}!", Toast.LENGTH_SHORT).show()
}
)
}
}
@Composable
fun NameInput(name: String, onNameChange: (String) -> Unit, onSubmit: () -> Unit) {
Column {
TextField(
value = name,
onValueChange = onNameChange,
label = { Text("Enter your name") }
)
Button(onClick = onSubmit, modifier = Modifier.padding(top = 8.dp)) {
Text("Submit")
}
}
}This example uses the state hoisting pattern by keeping the nameState in the NameInputScreen composable. The NameInput composable receives the current name and a function to update it as parameters. This way, NameInput is stateless and reusable.
When the user types, onNameChange updates the state in the parent. When the user taps Submit, a Toast shows the entered name using the current state.
This pattern helps separate UI from state management, making the code easier to test and maintain.