I need a TextField for currency in Android Compose. The TextField should behave: 1. If…
- User
I need a TextField for currency in Android Compose. The TextField should behave: 1. If it is empty is should show 0 with gray text color; 2. When user types the first number, it should turn black; 3. If the user removes all number, the text should stay black without 0, which is mentioned in the first case; 4. If the TextField loses focus and there is no number, the text should like in the first case(0 with gray color)
- Assistant
Here's a possible implementation of a currency TextField that meets all the mentioned requirements:
@Composable fun CurrencyTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier ) { val isFocused = LocalFocusManager.current.isFocused(LocalFocusScope.current) OutlinedTextField( value = value, onValueChange = { newValue -> onValueChange(newValue.trim()) }, label = { Text(text = "Amount") }, textStyle = if (value.isBlank() && !isFocused) LocalTextStyle.current.copy(color = Color.Gray) else LocalTextStyle.current, modifier = modifier, keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number), keyboardActions = KeyboardActions(onDone = { LocalFocusManager.current.clearFocus() }) ) { if (value.isBlank()) { Text( text = "0", style = LocalTextStyle.current.copy(color = Color.Gray), modifier = Modifier.alpha(if (isFocused) 1f else 0f) ) } } } - User
I need to show "0" if the real text is empty only once, when the user has not yet interacted with the TextField or if the user remove all number and changed the focus on another view
- Assistant
Here's an updated implementation of the
CurrencyTextFieldthat meets your new requirements:@Composable fun CurrencyTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier ) { var isDirty by remember { mutableStateOf(false) } val isFocused = LocalFocusManager.current.isFocused(LocalFocusScope.current) if (value.isEmpty() && !isDirty && !isFocused) { isDirty = true onValueChange("0") } OutlinedTextField( value = value, onValueChange = { newValue -> isDirty = true onValueChange(newValue.trim()) }, label = { Text(text = "Amount") }, textStyle = if (isFocused || isDirty) LocalTextStyle.current else LocalTextStyle.current.copy(color = Color.Gray), modifier = modifier, keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number), keyboardActions = KeyboardActions(onDone = { LocalFocusManager.current.clearFocus() }) ) DisposableEffect(Unit) { onDispose { if (value.isEmpty()) { isDirty = false onValueChange("") } } } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.