安卓开发 jetpack compose 帮我封装一个拖动LazyColumn的item可改变item位置组件,要求item长按开启拖动,kotlin代码编写完整代码,附上使用方法,最新代码
时间: 2023-06-13 10:06:18 浏览: 37
好的,我可以帮你实现这个功能。首先,我们需要用到 `LazyColumn` 和 `Box` 组件,`Box` 组件用于包裹我们的 `LazyColumn` 和拖动的 item。
以下是完整的代码实现:
```kotlin
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
@Composable
fun DragAndDropLazyColumn(
items: List<String>,
onItemsChanged: (List<String>) -> Unit
) {
var draggingIndex by remember { mutableStateOf(-1) }
var currentOffset by remember { mutableStateOf(Offset.Zero) }
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn {
items(items) { item ->
val index = items.indexOf(item)
val isDragging = index == draggingIndex
Column(
modifier = Modifier
.fillParentMaxWidth()
.pointerInput(Unit) {
forEachGesture {
awaitPointerEventScope {
awaitFirstDown()
draggingIndex = index
}
forEachGesture {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
currentOffset = event.calculateOffset()
when (event.action) {
androidx.compose.ui.input.pointer.PointerEvent
.Action.Up -> {
draggingIndex = -1
currentOffset = Offset.Zero
break
}
else -> Unit
}
}
}
}
}
}
.offset {
if (isDragging) currentOffset else Offset.Zero
}
) {
// your item content
}
}
}
}
LaunchedEffect(items, draggingIndex, currentOffset) {
if (draggingIndex != -1) {
val newIndex = items.indexOfFirst { item ->
item != items[draggingIndex] && item in draggingIndex..draggingIndex + 1
}
if (newIndex != -1) {
val newItems = items.toMutableList()
newItems.removeAt(draggingIndex)
newItems.add(newIndex, items[draggingIndex])
onItemsChanged(newItems)
}
}
}
}
```
使用方法:
```kotlin
DragAndDropLazyColumn(
items = listOf("item1", "item2", "item3"),
onItemsChanged = { newItems ->
// do something with newItems
}
)
```
其中,`items` 是你要展示的数据列表,`onItemsChanged` 是当用户拖拽 item 时,重新排列后的新数据列表。