android 我怎么能检测滑动手势的合成磨损,只有1个功能

icomxhvb  于 2023-01-24  发布在  Android
关注(0)|答案(1)|浏览(135)

我要监视整个屏幕。并检测是否有滑动手势发生。
我怎么能在一个函数中做到这一点呢?简单,简短,可读性强会很棒。
如果你能解释一下这个步骤,让我更好地理解需要为此做些什么,那就太好了。

nukf8bse

nukf8bse1#

您可以在顶层容器上使用Modifier.swipeable的WearMaterialApi:

val swipeState = SwipeableState<String>("initial")
val anchors = mapOf(0f to "left", 1f to "right")

Column(
modifier = Modifier.swipeable(
    state = swipeState,
    anchors = anchors,
    orientation = Orientation.HORIZONTAL,
    enabled = true,
    reverseDirection = false,
    interactionSource = null,
    thresholds = { _, _ -> 
    FractionalThreshold(0.5f) },
    resistance = resistanceConfig(anchors.keys),
    velocityThreshold = Dp(200)
  )
) {
  Text(swipeState.value)
 }

它允许您定义表示滑动选项边界的锚点Map。
您可以围绕swipstate的值创建UI逻辑
在本例中,如果发生向右滑动,文本将显示向右,如果发生向左滑动,文本将显示向左。
如果你想同时检测垂直和水平滑动,你可以在一个组合对象上使用两个Modifier.swipeable,方法是使用Modifier.then,如下所示:

val horizontalSwipeState = 
SwipeableState<String>("initial")
val horizontalAnchors = mapOf(0f to "left", 
1f to "right")
val verticalSwipeState = SwipeableState<String>("initial")
val verticalAnchors = mapOf(0f to "up", 1f     to "down")

Box(
modifier = Modifier
    .swipeable(
        state = horizontalSwipeState,
        anchors = horizontalAnchors,
        orientation =     Orientation.HORIZONTAL,
        enabled = true,
        reverseDirection = false,
        interactionSource = null,
        thresholds = { _, _ -> FractionalThreshold(0.5f) },
        resistance = resistanceConfig(horizontalAnchors.keys),
        velocityThreshold = Dp(200)
    )
    .then(
        Modifier.swipeable(
            state = verticalSwipeState,
            anchors = verticalAnchors,
            orientation = Orientation.VERTICAL,
            enabled = true,
            reverseDirection = false,
            interactionSource = null,
            thresholds = { _, _ -> FractionalThreshold(0.5f) },
            resistance = resistanceConfig(verticalAnchors.keys),
            velocityThreshold = Dp(200)
        )
    )
) {
Text("Horizontal:                         
${horizontalSwipeState.value} Vertical: 
 ${verticalSwipeState.value}")
}

并对每个方向使用不同的阈值,以避免两次滑动彼此重叠
更多信息:https://developer.android.com/reference/kotlin/androidx/wear/compose/material/package-summary#(androidx.compose.ui.修饰符).可滑动(androidx.wear.compose.material.swipeableState、kotlin.collections、Map、androidx.compose.foundation.gestures、方向、kotlin.布尔型、kotlin.布尔型、androidx.compose.found.interaction.mutableinteractionsource、kotlin.Function2、androidx.wear.compose.material.ResistanceConfig.androidx.compose.ui.unit.Dp)

相关问题