Okay, let's apply the focus-saving mechanism to your ValidatedOutlinedTextField implementation.
We need to:
- Introduce a
FocusRequester.
- Use
rememberSaveable to store a boolean indicating if the field had focus.
- Use
Modifier.onFocusChanged to update this saved state.
- Use
LaunchedEffect to request focus if the saved state indicates it should be focused.
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
// *** Import necessary focus APIs ***
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
// *** Import LaunchedEffect ***
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
// Assuming ValidationErrorViewData, SupportingErrorText, SaveButton are defined elsewhere
@Composable
private fun ValidatedOutlinedTextField(
originalValue: String,
onValueChange: (String) -> String,
modifier: Modifier = Modifier,
label: @Composable () -> Unit,
validationError: ValidationErrorViewData?,
isErrorApplicable: () -> Boolean,
keyboardOptions: KeyboardOptions,
onSave: (String) -> Unit,
onClearError: () -> Unit
) {
// Stores the last committed (saved) value
var committedValue by rememberSaveable { mutableStateOf(originalValue) }
// Stores the TextField's current text and cursor/selection state
// Uses TextFieldValue.Saver to correctly save text, selection, and composition
var textFieldValue by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue(committedValue, TextRange(committedValue.length)))
}
// --- Focus State Management ---
val focusRequester = remember { FocusRequester() }
// State to track if the TextField *was* focused before configuration change
// Use rememberSaveable to persist this state across rotations/process death
var hasFocusState by rememberSaveable { mutableStateOf(false) }
// --- End Focus State Management ---
val errorApplicable = isErrorApplicable()
val isErrorState = validationError != null && errorApplicable
OutlinedTextField(
value = textFieldValue,
onValueChange = { newValue ->
// Clear error if applicable and text actually changes
if (isErrorState && newValue.text != textFieldValue.text) {
onClearError()
}
// Apply the value transformation (e.g., normalization)
textFieldValue = newValue.copy(text = onValueChange(newValue.text))
},
modifier = modifier
// --- Add focus modifiers ---
.focusRequester(focusRequester)
.onFocusChanged { focusState ->
// Update our saved state variable when the actual focus state changes
hasFocusState = focusState.isFocused
}
// --- End focus modifiers ---
,
label = label,
shape = MaterialTheme.shapes.extraLarge,
trailingIcon = {
// Show save icon only if the current text differs from the committed value
if (textFieldValue.text != committedValue) {
SaveButton( // Replace with your actual SaveButton composable
onClick = {
val finalValue = textFieldValue.text
onSave(finalValue)
committedValue = finalValue // Update committed value
// Optional: You might want to remove focus after saving
// focusRequester.freeFocus()
}
)
}
},
keyboardOptions = keyboardOptions,
singleLine = true,
isError = isErrorState,
supportingText = {
if (validationError != null && errorApplicable) {
SupportingErrorText(validationError) // Replace with your actual SupportingErrorText
} else {
// Ensure consistent spacing even when no error text is shown
Spacer(modifier = Modifier.height(16.dp)) // Adjust height if needed
}
}
)
// --- LaunchedEffect to restore focus ---
// This effect runs when the composable enters the composition.
// If 'hasFocusState' is true (meaning it was focused before rotation),
// it requests focus for the TextField.
LaunchedEffect(Unit) {
if (hasFocusState) {
// Request focus using the focusRequester
focusRequester.requestFocus()
// Note: Sometimes a small delay might be needed if focus isn't restored immediately,
// but try without it first. Example:
// java.util.concurrent.Executors.newSingleThreadScheduledExecutor().schedule({
// focusRequester.requestFocus()
// }, 100, java.util.concurrent.TimeUnit.MILLISECONDS)
}
}
}
// --- Dummy implementations for required components ---
// Replace these with your actual composable implementations
data class ValidationErrorViewData(val message: String)
@Composable
fun SupportingErrorText(validationError: ValidationErrorViewData) {
// Example: Text(validationError.message, color = MaterialTheme.colorScheme.error)
Spacer(modifier = Modifier.height(16.dp)) // Placeholder
}
@Composable
fun SaveButton(onClick: () -> Unit) {
// Example: IconButton(onClick = onClick) { Icon(Icons.Default.Check, contentDescription = "Save") }
Spacer(modifier = Modifier.height(16.dp)) // Placeholder
}