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
You can achieve this by using a custom TextField in your Android Compose code. Here is an example of how to create a currency TextField that meets your requirements:
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun CurrencyTextField( modifier: Modifier = Modifier, onCurrencyChange: (String) -> Unit, onFocusChanged: (Boolean) -> Unit ) { var currencyText by remember { mutableStateOf("") } var isFocused by remember { mutableStateOf(false) } var isTextBlack by remember { mutableStateOf(false) } val textFieldValue = if (isFocused || isTextBlack) { currencyText } else { "0" } val textColor = if (isTextBlack || isFocused) { Color.Black } else { Color.Gray } OutlinedTextField( value = textFieldValue, onValueChange = { newValue -> currencyText = newValue onCurrencyChange(newValue) isTextBlack = newValue.isNotEmpty() }, singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), keyboardActions = KeyboardActions(onDone = { isFocused = false onFocusChanged(isFocused) }), modifier = modifier.padding(8.dp), textAlign = TextAlign.Center, cursorColor = textColor, textStyle = androidx.compose.ui.text.TextStyle( color = textColor ), ) }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.