I'm trying make BasicTextField select all contents when user taps on it.
This happens automatically if user will long press on the contents of BasicTextField but I want it happening without the long press.
There's a thread Select all text of TextField in Jetpack Compose but it utilizes TextFieldValue object which is hidden in BasicTextField but can be passed in TextField composable.
CodePudding user response:
You can use the TextFieldValue also with a BasicTextField.
Instead of using the onFocusChanged modifier you can use the interactionSource and change the selection range depending on it.
Something like:
var textFieldValue by remember { mutableStateOf(TextFieldValue("Custom text")) }
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
LaunchedEffect(isFocused) {
val endRange = if (isFocused) textFieldValue.text.length else 0
textFieldValue = textFieldValue.copy(
selection = TextRange(
start = 0,
end = endRange
)
)
}
BasicTextField(
value = textFieldValue,
onValueChange = { textFieldValue = it },
interactionSource = interactionSource
)
