1

我正在尝试TextField使用以下功能在 Jetpack Compose 中实现 a:起初它被禁用,但是当用户按下 时Button,它会被启用并同时获得焦点。这是我的方法:

var text by remember { mutableStateOf("text") }
var enabled by remember { mutableStateOf(false)}
val focusRequester = remember { FocusRequester() }

Column {
    TextField(
        value = text,
        onValueChange = { text = it },
        enabled = enabled,
        modifier = Modifier.focusRequester(focusRequester),
        textStyle = TextStyle(fontSize = 24.sp)
    )
    Button(onClick = {
        enabled = true
        focusRequester.requestFocus()
    }) {
        Text("Enable and request focus")
    }

但是当按下按钮时,TextField只有启用,而不是集中。要聚焦它,用户必须再次单击它。我做错了什么,可能的解决方法是什么?

在此处输入图像描述

4

3 回答 3

4

您必须聆听enabled参数的变化才能将焦点放在TextField.

您可以将代码更改为:

    Button(onClick = {
        enabled = true

    }) {
        Text("Enable and request focus")
    }

    DisposableEffect(enabled) {
        if (enabled){
            focusRequester.requestFocus()
        }
        onDispose {}
    }
于 2022-01-10T16:56:57.827 回答
1

只需在启用文本字段后添加延迟,如下所示:

var text by remember { mutableStateOf("text") }
var enabled by remember { mutableStateOf(false)}
val focusRequester = remember { FocusRequester() }
val scope = rememberCoroutineScope()

Column {
    TextField(
        value = text,
        onValueChange = { text = it },
        enabled = enabled,
        modifier = Modifier.focusRequester(focusRequester),
        textStyle = TextStyle(fontSize = 24.sp)
    )
    Button(onClick = {
        scope.launch {
            enabled = true
            delay(100)
            focusRequester.requestFocus()
        }
    }) {
        Text("Enable and request focus")
    }
}
于 2022-01-10T16:04:37.937 回答
0

我曾经遇到过类似的问题,我通过使用interactionSource. 代码看起来像这样:

var text by remember { mutableStateOf("text") }
var enabled by remember { mutableStateOf(false)}
val focusRequester = remember { FocusRequester() }
val interactionSource = remember { MutableInteractionSource() } // add this

Column {
    TextField(
        value = text,
        onValueChange = { text = it },
        enabled = enabled,
        modifier = Modifier
            .focusable(interactionSource = interactionSource) // and this
            .focusRequester(focusRequester),
        textStyle = TextStyle(fontSize = 24.sp)
    )
    ...

IIRC 拥有正确的顺序很重要.focusable().focusRequester()但不记得到底是哪个,所以如果不能立即工作,请尝试交换它们。

于 2022-01-10T15:50:51.733 回答