Jetpack Compose TextField中的android:selectAllOnFocus是什么?

3

传统的Android中的EditText支持 android:selectAllOnFocus 属性,当用户点击 EditText 时,其内容将被选中。

在Jetpack Compose中使用androidx.compose.material.TextField如何实现这种行为?

1个回答

6
你可以从 MutableInteractionSource 收集焦点状态,并根据其更改选择状态:
var textFieldValue by remember { mutableStateOf(TextFieldValue("Lorem ipsum")) }
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
LaunchedEffect(isFocused) {
    textFieldValue = textFieldValue.copy(
        selection = if (isFocused) {
            TextRange(
                start = 0,
                end = textFieldValue.text.length
            )
        } else {
            TextRange.Zero,
        }
    )
}
TextField(
    value = textFieldValue,
    onValueChange = { textFieldValue = it },
    interactionSource = interactionSource,
)

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