Jetpack Compose TextField 中的 android:selectAllOnFocus

Pio*_*ski 4 android android-jetpack-compose

Android 上的传统EditText支持android:selectAllOnFocus属性,这会导致当用户单击 时选择其内容EditText

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

Phi*_*hov 7

您可以从中收集焦点状态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,
)
Run Code Online (Sandbox Code Playgroud)