您需要实现可侧滑删除的Android Compose列表项。以下是一个简单的实现:
-
创建一个自定义的列表项组件,例如
SwipeableListItem
。 -
在
SwipeableListItem
组件中添加一个SwipeableState
对象,用于跟踪侧滑状态。 -
在
SwipeableListItem
组件中添加一个Modifier
,使其可滑动。
Modifier.swipeable(
state = swipeableState,
anchors = mapOf(
0f to SwipeDirection.Left,
width.toFloat() to SwipeDirection.Right
),
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
- 添加一个删除按钮,当侧滑距离超过阈值时,显示出来。
if (swipeableState.targetValue == SwipeDirection.Left) {
Box(
modifier = Modifier
.fillMaxHeight()
.background(MaterialTheme.colors.error)
.align(Alignment.CenterEnd)
.padding(end = 16.dp)
.clickable { onDelete() }
) {
Icon(
Icons.Default.Delete,
contentDescription = "Delete",
tint = Color.White,
modifier = Modifier.padding(16.dp)
)
}
}
完整代码示例:
@Composable
fun SwipeableListItem(
text: String,
onDelete: () -> Unit
) {
val swipeableState = rememberSwipeableState(initialValue = SwipeDirection.None)
Box(
modifier = Modifier
.fillMaxWidth()
.height(64.dp)
.swipeable(
state = swipeableState,
anchors = mapOf(
0f to SwipeDirection.Left,
width.toFloat() to SwipeDirection.Right
),
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
) {
Text(
text = text,
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.surface)
.padding(horizontal = 16.dp)
.align(Alignment.CenterStart)
)
if (swipeableState.targetValue == SwipeDirection.Left) {
Box(
modifier = Modifier
.fillMaxHeight()
.background(MaterialTheme.colors.error)
.align(Alignment.CenterEnd)
.padding(end = 16.dp)
.clickable { onDelete() }
) {
Icon(
Icons.Default.Delete,
contentDescription = "Delete",
tint = Color.White,
modifier = Modifier.padding(16.dp)
)
}
}
}
}
enum class SwipeDirection { Left, Right, None }