Compose 中 Migrate from Swipeable to AnchoredDraggable

350 阅读1分钟

在 Jetpack Compose 中,从 Swipeable 迁移到 AnchoredDraggable 的过程是将已弃用的 Swipeable 修饰符替换为 AnchoredDraggable 修饰符。这个迁移过程能够实现类似的拖拽行为,同时提供更灵活和更多控制的拖拽功能。以下是详细的步骤以及示例代码:

第一步:替换 Swipeable 为 AnchoredDraggable

将您的 Composable 函数中的 Swipeable 使用替换为 AnchoredDraggable

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.tween
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.offset
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp

@Composable
fun AnchoredDraggableExample() {
    val offsetX = remember { Animatable(0f) }
    val draggableState = rememberDraggableState {
        offsetX.snapTo(it)
    }

    Box(
        modifier = Modifier
            .offset(x = offsetX.value.dp)
            .anchorable(
                state = draggableState,
                orientation = Orientation.Horizontal,
                anchors = listOf(-200f, 0f, 200f),
                animationSpec = tween(durationMillis = 300)
            )
            .then(Modifier.fillMaxSize())
            .background(Color.Blue)
    )
}

第二步:调整参数

  • rememberSwipeableState() 替换为 rememberDraggableState()
  • anchors 参数替换为要拖拽项应该捕捉到的锚点值的列表。
  • 根据您的具体需求调整任何其他参数。

第三步:更新使用方式

更新与 SwipeableState 交互的任何代码,以适应新的 AnchoredDraggableState

结论

通过按照这些步骤操作,您可以在 Jetpack Compose 中成功将使用 Swipeable 迁移到使用 AnchoredDraggable。这种迁移确保您的应用程序与最新的 Compose API 保持一致,同时保持所需的拖拽行为。在迁移后,请确保充分测试您的应用程序,以确保一切正常运行。