Artier
Artier

Reputation: 1673

Unable to make draggable box Andoid Studio, Kotlin

I have code I want to add draggable box but it is not able to create draggable box, Something is missing in code

a code I want to make draggable box but in screen it show nothing

val state = rememberDraggableState()


Box(modifier = Modifier.draggable(
    state = state,
    orientation = Orientation.Vertical,
    onDragStarted = { Log.d("Box", "Starting Drag") },
    onDragStopped = { Log.d("Box", "Finishing Drag") }
))

Upvotes: 0

Views: 90

Answers (1)

Chirag Thummar
Chirag Thummar

Reputation: 3282

When you want to drag or move any element you need to set its Offset value so first you are missing it and then how to update and when to update it.

Let's break down the example

  1. Define offsetY and set Initial value to 0f
  2. Define the onDelta method of rememberDraggableState and when drag stopped it will return a delta which we will used to add in current offsetY value and update it
  3. Set the composable offset using the offsetY value

Code

@Preview
@Composable
fun Stack011(modifier: Modifier = Modifier) {

    var offsetY by remember { mutableStateOf(0f) }
        val state = rememberDraggableState(onDelta = {delta->
        offsetY += delta
    })

    Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        Box(modifier = Modifier
            .size(50.dp)
            .offset { IntOffset(0, offsetY.roundToInt()) }
            .background(color = Color.Red)
            .draggable(
                state = state,
                orientation = Orientation.Vertical,
                onDragStarted = { Log.d("Box", "Starting Drag") },
                onDragStopped = { Log.d("Box", "Finishing Drag") }
            ))
    }
}

Preview

preview

Upvotes: 0

Related Questions