So I have a compose layout let suppose A which has a text and a see more option. When clicking on it it should navigate to another compose where you can see the remaining text.
So there is edit option also and when trying to edit, I want the focus to be at the end of the text.
How to achieve that.
Below is the code which I am currently working on:
OutlinedTextField(
value = textFieldValue,
modifier = modifier,
onValueChange = {
textFieldValueState = it
if (value != it.text) {
onValueChange(it.text)
}
},
placeholder = placeholder,)
Below is the edit screen:
CodePudding user response:
To place the cursor at the end of the text, you must use TextFieldValue
The following code, give the focus to the TextField and place the cursor at the end of the text :
@Composable
fun TestTextField(title: String = "Hello") {
val titleFocusRequester = remember { FocusRequester() }
val titleTextFieldValueState = remember {
mutableStateOf(
TextFieldValue(
text = title,
selection = TextRange(title.length)
)
)
}
LaunchedEffect(Unit) {
titleFocusRequester.requestFocus()
}
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
TextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(titleFocusRequester),
value = titleTextFieldValueState.value,
onValueChange = { tfv: TextFieldValue ->
titleTextFieldValueState.value = tfv
}
)
}
}
CodePudding user response:
You can use the selection parameter in the TextFieldValue
class:
selection
- the selection range. If the selection is collapsed, it represents cursor location. When selection range is out of bounds, it is constrained with the text length.
Something like:
val content = "content"
var text by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue(content, TextRange(content.length)))
}
val focusRequester = remember { FocusRequester() }
OutlinedTextField(
value = text,
onValueChange = { text = it },
label = { Text("Label") },
modifier = Modifier.focusRequester(focusRequester),
)
To give the focus you can use:
LaunchedEffect(Unit) {
requester.requestFocus()
}