在 Jetpack Compose 中选择 TextField 的所有文本 [英] Select all text of TextField in Jetpack Compose

查看:64
本文介绍了在 Jetpack Compose 中选择 TextField 的所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Jetpack Compose 中使用 TextField 组件.获得焦点时如何选择所有文本?

I'm using TextField component in Jetpack Compose. How to select all text when it receive focus?

推荐答案

在这种情况下,你应该使用 TextFieldValue 作为你的 TextField 的状态,当它获得焦点时,您可以使用 TextFieldValue 状态设置 selection.

In this case you should use TextFieldValue as state of your TextField, and when it receive focus, you set the selection using the TextFieldValue state.

val state = remember {
    mutableStateOf(TextFieldValue(""))
}
TextField(
    value = state.value,
    onValueChange = { text -> state.value = text },
    modifier = Modifier
        .onFocusChanged { focusState ->
            if (focusState.isFocused) {
                val text = state.value.text
                state.value = state.value.copy(
                    selection = TextRange(0, text.length)
                )
            }
        }
)

结果如下:

请注意,根据您触摸的情况,光标会转到触摸的位置,而不是选择整个文本.您可以尝试弄清楚这是错误还是功能:)

Notice that depending on you're touching the cursor goes to the touched position instead of select the entire text. You can try to figure it out if this is a bug or a feature :)

这篇关于在 Jetpack Compose 中选择 TextField 的所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆