Jetpack Compose:如何将光标定位在TextField的末尾

6
使用 Jetpack Compose 的 BasicTextField 组件,我想要创建以下效果:

初始文本

Initial text

然后输入一些值

Text with Value

然后,例如将光标移动到索引2处,并在末尾放置一个值(假设为3)。 我想要以下效果:

期望的效果

Desired effect

换句话说,我希望将值输入到当前索引,并强制光标移到末尾(如果需要可以再次更改光标位置并重复此过程)。我可以强制光标始终停留在末尾,但我不知道如何在Jetpack compose中实现这一点。
注意:我已经尝试使用TextRange的解决方案,但这会锁定我的选择。
提前感谢!

这个链接 https://dev59.com/mVEG5IYBdhLWcg3wMGPV 有帮助吗? - undefined
@Raghunandan,该解决方案限制了选择和手动更改光标位置,正如OP所提到的。 - undefined
@Abhimanyu 哎呀,那我刚才理解错了问题。 - undefined
@IGG,你找到你要找的答案了吗? - undefined
3个回答

4
要将光标移动到指定位置,可以使用TextRange(position)方法。例如,如果你想将光标移动到文本的末尾,可以执行以下操作:
TextField(
    value = TextFieldValue(
        text = textValue,
        selection = TextRange(textValue.length)
    ),
    onValueChange = {
        textValue = it.text
    }
)

1
最好的解决方案是
TextField(
    value = TextFieldValue(
        text = textValue,
        selection = TextRange(textValue.length). // TextRange(0, textValue.length) -> Select that text in a color
    ),
    onValueChange = {
        textValue = it.text
    }
)

如果它有效,请弥补它。

这个解决方案限制了手动选择和更改光标位置,正如OP所提到的。 - undefined

0
将光标放在TextField的末尾,并且能够选择、复制等操作的正确答案是:
var textFieldValueState by remember {
    mutableStateOf(TextFieldValue(text = textValue, selection = TextRange(textValue.length)))
}

TextField(
    value = textFieldValueState,
    onValueChange = { textFieldValueState = it }
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接