Last active
April 19, 2022 01:23
-
-
Save loloof64/d9ce748dc19b0f45df8548ad1b1375de to your computer and use it in GitHub Desktop.
A simple Drag and Drop in Jetpack compose 1.0.0-alpha07 (needing adding imports automatically from Android Studio - Canary channel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Preview | |
@Composable | |
fun DragNDropComponent() { | |
Column(modifier = Modifier.size(100.dp).background(Color.Red)) { | |
// The updatable Drag and Drop data | |
var x by remember{ mutableStateOf(0f)} | |
var y by remember { mutableStateOf(0f)} | |
// The offsets that is always update, that place the component to be dragged | |
val offsetX = with(DensityAmbient.current) { | |
x.toDp() | |
} | |
val offsetY = with(DensityAmbient.current) { | |
y.toDp() | |
} | |
Column(modifier = Modifier | |
// Placing the component to be dragged. | |
.offset(offsetX, offsetY) | |
.size(10.dp) | |
.background(Color.Blue) | |
.dragGestureFilter( | |
// The core Drag and Drop feature | |
object : DragObserver { | |
override fun onDrag(dragDistance: Offset): Offset { | |
x += dragDistance.x | |
y += dragDistance.y | |
return dragDistance | |
} | |
override fun onCancel() { | |
x = 0f | |
y = 0f | |
} | |
override fun onStart(downPosition: Offset) { | |
x = 0f | |
y = 0f | |
} | |
override fun onStop(velocity: Offset) { | |
x = 0f | |
y = 0f | |
} | |
} | |
) | |
){} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment