android:selectAllOnFocus in Jetpack Compose TextField



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

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

您可以从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,
)

最新更新