I have a BasicTextField in Jetpack compose. when I type a word a list of suggested words shows. when I select each site I need to replace the selected word with an uncompleted word. My problem is related to the cursor position. if I write a word with two chars and click on a word with four chars, the cursor stays after char number two and doesn’t move to the last char of the new word. how can I handle this?
Note: If it can help to answer, I convert the TextField words to a list of strings and keep the last edited list item in UiState
My TextField Component:
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DescriptionTextField(
modifier: Modifier = Modifier,
hint: String,
hintStyle: TextStyle = Typography.Regular22,
textStyle: TextStyle = Typography.Regular22,
hashtagMentionWordStyle: TextStyle = textStyle,
value: String,
onValueChange: (String) -> Unit,
caption: List<ActionableText>?,
focusRequester: FocusRequester = remember { FocusRequester() },
) {
val textFieldValueState by remember(value) {
mutableStateOf(
TextFieldValue(
text = value
)
)
}
Box(
modifier = modifier
.padding(horizontal = 8.dp)
.defaultMinSize(minHeight = 48.dp)
.height(IntrinsicSize.Min)
.background(color = Color.Transparent)
) {
if (textFieldValueState.text.isEmpty()) {
Text(
text = hint,
style = hintStyle,
color = white,
modifier = Modifier.align(Alignment.CenterStart)
)
} else {
val annotatedString = findHashtagAndMention(caption, hashtagMentionWordStyle)
Text(
text = annotatedString,
style = textStyle,
color = white,
modifier = Modifier.align(Alignment.CenterStart)
)
}
BasicTextField(
value = value,
onValueChange = onValueChange,
textStyle = textStyle.copy(color = Color.Transparent),
cursorBrush = SolidColor(green),
modifier = Modifier
.fillMaxWidth()
.background(color = Color.Transparent)
.padding(0.dp)
.align(Alignment.CenterStart)
)
}
}
@Composable
private fun findHashtagAndMention(
displayedCaption: List<ActionableText>?,
hashtagMentionWordStyle: TextStyle
): AnnotatedString {
val annotatedString = buildAnnotatedString {
displayedCaption?.forEachIndexed { index, part ->
if (part.type == ActionableTextType.TAG || part.type == ActionableTextType.PERSON) {
withStyle(style = SpanStyle(color = hashtagMentionWordStyle.color)) {
append(part.value)
}
} else {
append(part.value)
}
if (index != displayedCaption.size - 1) {
append(" ")
}
}
}
return annotatedString
}
and Usage:
DescriptionTextField(
modifier = Modifier
.padding(PaddingValues(horizontal = 16.dp))
.heightIn(max = 200.dp),
hint = stringResource(id = R.string.core_ui_say_some_thing),
value = uiState.caption?.list?.joinToString(separator = " ") {
it.value
} ?: "",
hashtagMentionWordStyle = textStyle.copy(color = green),
caption = uiState.caption?.list,
onValueChange = {
onIntent(EnterPostDescriptionIntent.OnCaptionChange(it))
},
)