android 无法创建可拖动框Andoid Studio,Kotlin

wko9yo5t  于 2024-01-04  发布在  Android
关注(0)|答案(1)|浏览(125)

我有代码,我想添加可拖动框,但它无法创建可拖动框,代码中缺少一些东西
一个代码,我想使拖动框,但在屏幕上它显示什么都没有

  1. val state = rememberDraggableState()
  2. Box(modifier = Modifier.draggable(
  3. state = state,
  4. orientation = Orientation.Vertical,
  5. onDragStarted = { Log.d("Box", "Starting Drag") },
  6. onDragStopped = { Log.d("Box", "Finishing Drag") }
  7. ))

字符串

ippsafx7

ippsafx71#

当你想拖动或移动任何元素时,你需要设置它的偏移值,这样你就可以首先忽略它,然后如何更新以及何时更新它。
让我们分解这个例子
1.定义offsetY并将初始值设置为0f
1.定义rememberDraggableStateonDelta方法,当拖动停止时,它将返回一个delta,我们将使用它来添加当前offsetY值并更新它
1.使用offsetY值设置composable偏移

验证码

  1. @Preview
  2. @Composable
  3. fun Stack011(modifier: Modifier = Modifier) {
  4. var offsetY by remember { mutableStateOf(0f) }
  5. val state = rememberDraggableState(onDelta = {delta->
  6. offsetY += delta
  7. })
  8. Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
  9. Box(modifier = Modifier
  10. .size(50.dp)
  11. .offset { IntOffset(0, offsetY.roundToInt()) }
  12. .background(color = Color.Red)
  13. .draggable(
  14. state = state,
  15. orientation = Orientation.Vertical,
  16. onDragStarted = { Log.d("Box", "Starting Drag") },
  17. onDragStopped = { Log.d("Box", "Finishing Drag") }
  18. ))
  19. }
  20. }

字符串

预览


的数据

展开查看全部

相关问题