传统的Android中的EditText
支持 android:selectAllOnFocus 属性,当用户点击 EditText
时,其内容将被选中。
在Jetpack Compose中使用androidx.compose.material.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,
)