从 Compose bom 版本
implementation platform('androidx.compose:compose-bom:2024.01.00')
开始,现在原生支持在任何 Modifier.dragAndDropSource
元素上实现 Modifier.dragAndDropTarget
和 Composable
。
请参阅下面的演示:
Text(
modifier = Modifier
.height(60.dp)
.fillMaxWidth()
.background(Color.Yellow)
.dragAndDropSource {
detectTapGestures(
onLongPress = {
startTransfer(
DragAndDropTransferData(
ClipData(
"",
arrayOf("array of mimeTypes - those tell dragAndDropTargets which type of dragAndDropSource this is, such as an image, text, phone number, or your custom type"),
ClipData.Item("you can add new clip items with data here")
)
)
)
}
)
},
color = Color.Black,
textAlign = TextAlign.Center,
text = "Hold me to drag and drop"
)
val enteredIndex = remember {
mutableIntStateOf(-1)
}
LazyColumn {
items(50) {
Text(
modifier = Modifier
.then(
if (enteredIndex.intValue == it) {
Modifier.background(Color.White)
} else Modifier.background(Color.Cyan)
)
.fillMaxWidth()
.height(80.dp)
.dragAndDropTarget(
shouldStartDragAndDrop = {
true
},
target = object : DragAndDropTarget {
override fun onDrop(event: DragAndDropEvent): Boolean {
enteredIndex.intValue = -1
return true
}
override fun onEntered(event: DragAndDropEvent) {
super.onEntered(event)
enteredIndex.intValue = it
}
override fun onExited(event: DragAndDropEvent) {
super.onExited(event)
enteredIndex.intValue = -1
}
}
),
color = Color.Black,
textAlign = TextAlign.Center,
text = "Content $it, that responds to drag and drop"
)
}
}
将
MutableState
保持在 LazyColumn
项目的回收状态之外是维护引用和状态的安全方法。将其放入每个项目中会导致其掉落 MutableState
并且不响应其更改。
请注意,您也可以拖放到其他应用程序,请参阅 Google 的博客以进一步阅读:https://android-developers.googleblog.com/2024/01/whats-new-in-jetpack-compose-一月 24 日发布.html.