DragAndDropTarget не срабатывает в синтаксисе перетаскиванияAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 DragAndDropTarget не срабатывает в синтаксисе перетаскивания

Сообщение Anonymous »

Код: Выделить всё

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ZoomableRotatableImage(urisList: SnapshotStateList?, currentIndex: Int) {
var zoom by remember { mutableStateOf(1f) }
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
var rotation by remember { mutableStateOf(0f) }
val minScale = 0.5f
val maxScale = 2f
val context = LocalContext.current

// Remember dragged image index
var draggedIndex by remember { mutableStateOf(-1) } // Initialize to an invalid index

val imagePainter = rememberAsyncImagePainter(urisList?.get(currentIndex))

Image(
painter = imagePainter,
contentDescription = "Image $currentIndex",
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxSize()
.graphicsLayer(
scaleX = zoom,
scaleY = zoom,
translationX = offsetX,
translationY = offsetY,
rotationZ = rotation
)
.pointerInput(Unit) {
detectTransformGestures { _, pan, gestureZoom, gestureRotate ->
zoom = (zoom * gestureZoom).coerceIn(minScale, maxScale)
rotation += gestureRotate
offsetX += pan.x * zoom
offsetY += pan.y * zoom
}
}
.dragAndDropSource {
detectTapGestures(
onLongPress = {
draggedIndex = currentIndex // Store the index of the dragged image
Log.d("DRAG_EVENT", "Dragging image at index $draggedIndex")
startTransfer(
DragAndDropTransferData(
clipData = ClipData.newIntent(
"imageTransfer",
Intent().apply {
putExtra("imageResId", urisList?.get(currentIndex)) // Pass the image URI
}
)
)
)
}
)
}
.dragAndDropTarget(
shouldStartDragAndDrop = { true },
target = object : DragAndDropTarget {
override fun onDrop(event: DragAndDropEvent): Boolean {
Log.d("DRAG_EVENT", "Dropped on index $currentIndex")

// Only swap if dragging from a different index
if (draggedIndex != -1 && draggedIndex != currentIndex) {
urisList?.let {
// Swap images in the urisList
val temp = it[draggedIndex]
it[draggedIndex] = it[currentIndex]
it[currentIndex] = temp
Log.d("DRAG_EVENT", "Swapped images: $draggedIndex  $currentIndex")
}
}
// Reset dragged index
draggedIndex = -1
return true
}
}
)
)
}
  • Я реализовал перетаскивание с помощью dragAndDropSource и dragAndDropTarget Jetpack Compose. Я добавил логирование в начало перетаскивания (

    Код: Выделить всё

    onLongPress
    ) и удалить событие (), чтобы проверить, когда изображение перетаскивается.
  • Инициирование перетаскивания работает нормально, и я могу видеть журналы событие onLongPress в dragAndDropSource, но журналы внутри метода onDrop внутри dragAndDropTarget не печатаются, когда я пытаюсь переместить изображение на другую цель.


Подробнее здесь: https://stackoverflow.com/questions/790 ... get-syntax
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»