InteractionState 被移除后,在 Jetpack Compose Beta 1 中提升按下状态

Hoist pressed state in Jetpack Compose Beta 1 after InteractionState was removed

在 compose-beta01 之前,使用 InteractionState:

在 Jetpack Compose 中提升按下状态非常容易
@Composable
fun App() {
    val interactionState = remember { InteractionState() }
    val pressed = interactionState.contains(Interaction.Pressed)

    MyComposable(Modifier.clickable(interactionState = interactionState) { })
}

InteractionState 在 beta01 中被删除,现在有明显的方法可以复制此行为。如何使用 clickable 修饰符提升按下状态?

您是否尝试应用 Compose beta01 发行说明中的​​说明?

InteractionState has been replaced with [Mutable]InteractionSource

  • Interfaces are responsible for emitting / collecting Interaction events.
  • Instead of passing interactionState = remember { InteractionState() } to components such as Button and Modifier.clickable(), use interactionSource = remember { MutableInteractionSource() }.
  • Instead of: Interaction.Pressed in interactionState you should instead use the extension functions on InteractionSource, such as InteractionSource.collectIsPressedAsState().
  • For complex use cases you can use InteractionSource.interactions to observe the stream of Interactions. See the InteractionSource documentation and samples for more information.
  • (I85965, b/152525426, b/171913923, b/171710801, b/174852378)

因此,在您的示例中,我会尝试类似的操作:

val interactionSource = remember { MutableInteractionSource() }
val pressedState = interactionSource.collectIsPressedAsState()

MyComposable(
    Modifier.clickable(
        interactionSource = interactionSource,
        indication = LocalIndication.current
    ) {}
)