//dp转px
val Int.toPx: Float
get() {
var scale = 1f
context.resources.displayMetrics.apply {
scale = density
}
return this * scale
}
@Preview
@Composable
fun TestUI(){
Column(Modifier.fillMaxSize(),verticalArrangement = Arrangement.Center) {
SwipeToDeleteItem(
content = {
Row(
modifier = Modifier.height(30.dp)
.padding(12.dp)
) {
}
},
onDelete = {
}
)
}
}
@Composable
fun SwipeToDeleteItem(
content: @Composable (RowScope.() -> Unit),
onDelete: () -> Unit
) {
val swipeState = remember { Animatable(0f) }
val coroutineScope = rememberCoroutineScope()
val swipeThreshold = (-60).toPx
val focusRequester = remember { FocusRequester() }
Box(
modifier = Modifier
.focusRequester(focusRequester)
.onFocusChanged {
if (!it.isFocused) {
coroutineScope.launch {
swipeState.animateTo(0f, animationSpec = tween(300))
}
}
}
.focusable()
.fillMaxWidth()
.padding(12.dp)
.clip(RoundedCornerShape(12.dp))
.height(60.dp),
contentAlignment = Alignment.CenterEnd,
) {
Box(
modifier = Modifier
.fillMaxSize()
.background(color = Color(0xFFD54941)),
contentAlignment = Alignment.CenterEnd
) {
Text(
"删除",
modifier = Modifier
.width(60.dp)
.throttleClick {
coroutineScope.launch {
swipeState.animateTo(0f, animationSpec = tween(300))
}
onDelete()
},
textAlign = TextAlign.Center,
style = TextStyle(color = Color(0xFFFFFFFF))
)
}
Row(
modifier = Modifier
.offset {
IntOffset(swipeState.value.toInt(), 0)
}
.fillMaxSize()
.background(Color(0xFFFFFFFF))
.draggable(
orientation = Orientation.Horizontal,
state = rememberDraggableState { delta ->
coroutineScope.launch {
if (delta < 0 || swipeState.value + delta < 0) {
swipeState.snapTo(swipeState.value + delta)
}
}
},
onDragStopped = {
coroutineScope.launch {
focusRequester.requestFocus()
if (swipeState.value < swipeThreshold) {
swipeState.animateTo(swipeThreshold, animationSpec = tween(300))
} else {
swipeState.animateTo(0f, animationSpec = tween(300))
}
}
}
),
content = content
)
}
}
Aandroid Compose 侧滑删除按钮
最新推荐文章于 2025-08-05 19:53:28 发布