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,
)