重构后如何保持对元素的关注?

How to keep focus on an element after recompose?

我的 Compose 桌面应用程序中有一个自定义组件,它可以具有焦点:

val focusRequester = remember { FocusRequester() }
var focused by remember { mutableStateOf(false) }
Row(modifier.fillMaxWidth()
    .focusRequester(focusRequester)
    .onFocusChanged { state -> focused = state.isFocused }

这如您所料。但是,当我根据 focused 状态添加边框时,它会中断:

val focusRequester = remember { FocusRequester() }
var focused by remember { mutableStateOf(false) }
Row(Modifier.fillMaxWidth()
    .focusRequester(focusRequester)
    .onFocusChanged { state -> focused = state.isFocused }
    .border(if (focused) 1.dp else 0.dp, MaterialTheme.colors.primary)

据我所知,重组实际上导致 onFocusedChanged 再次触发 isFocused = false。所以这就是问题所在,而不是 focused 属性 本身的记忆。

我的组件如何在重新组合绘制边框后保持焦点?

您可以使用 interactionSource.collectIsFocusedAsState() 而不是 onFocusChanged修饰符。

类似于:

val focusRequester = remember { FocusRequester() }
val interactionSource = remember { MutableInteractionSource() }
val focused by interactionSource.collectIsFocusedAsState()

    Row(Modifier
         // add focusRequester modifier before the focusable (or even in the parent)
        .focusRequester(focusRequester)
        .focusable(interactionSource = interactionSource)
        .border(if (focused) 1.dp else 0.dp, MaterialTheme.colors.primary)