简体   繁体   中英

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

Until compose-beta01 it was very easy to hoist the pressed state in Jetpack Compose using InteractionState :

@Composable
fun App() {
    val interactionState = remember { InteractionState() }
    val pressed = interactionState.contains(Interaction.Pressed)

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

InteractionState was removed in beta01 and there is now obvious way to replicate this behaviour. How can I hoist the pressed state using the clickable modifier?

Have you tried applying what's explained in the release notes of 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 )

So, in your example, I would try something like:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM