OutlinedTextField 自动对焦

OutlinedTextField Autofocus

所以我有一个撰写布局,让我们假设 A 有一个文本和一个查看更多选项。单击它时,它应该导航到另一个撰写,您可以在其中看到剩余的文本。

因此还有编辑选项,当我尝试编辑时,我希望焦点位于文本的末尾。

如何实现。

下面是我目前正在处理的代码:

OutlinedTextField(
value = textFieldValue,
modifier = modifier,
onValueChange = {
    textFieldValueState = it
    if (value != it.text) {
        onValueChange(it.text)
    }
},
placeholder = placeholder,)

编辑画面如下:

要将光标置于文本末尾,必须使用TextFieldValue

以下代码,将焦点置于 TextField 并将光标置于文本末尾:

@Composable
fun TestTextField(title: String = "Hello") {
    val titleFocusRequester = remember { FocusRequester() }

    val titleTextFieldValueState = remember {
        mutableStateOf(
            TextFieldValue(
                text = title,
                selection = TextRange(title.length)
            )
        )
    }

    LaunchedEffect(Unit) {
        titleFocusRequester.requestFocus()
    }

    Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        TextField(
            modifier = Modifier
                .fillMaxWidth()
                .focusRequester(titleFocusRequester),
            value = titleTextFieldValueState.value,
            onValueChange = { tfv: TextFieldValue ->
                titleTextFieldValueState.value = tfv
            }
        )
    }
}

您可以使用 TextFieldValue class 中的选择参数:

selection - the selection range. If the selection is collapsed, it represents cursor location. When selection range is out of bounds, it is constrained with the text length.

类似于:

val content = "content"
var text by rememberSaveable(stateSaver = TextFieldValue.Saver) {
    mutableStateOf(TextFieldValue(content, TextRange(content.length)))
}

val focusRequester = remember { FocusRequester() }

OutlinedTextField(
    value = text,
    onValueChange = { text = it },
    label = { Text("Label") },
    modifier = Modifier.focusRequester(focusRequester),
)

要给出焦点,您可以使用:

LaunchedEffect(Unit) {
     requester.requestFocus()
}