Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Drag and Drop in Jetpack compose 1.0.0-alpha07 (needing adding imports automatically from Android Studio - Canary channel)
@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