我有一个按类别显示项目的列表。如果我选择第一个类别并将第一个项目向左滑动,然后将一个类别更改为另一个类别。新列表正在更新,但第一个项目在新列表 ui 上保持滑动状态,应将所有可滑动项目显示为默认状态。类别更改时如何设置默认滑动状态?
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SwipeRevealDismissItem(
context: Context,
itemDataClass: itemDataClass,
onDelete: (itemDataClass: itemDataClass) -> Unit,
isEnabled: Boolean,
defaultState: Int = SwipeState.DEFAULT.value,
onItemSelected: ((itemDataClass?) -> Unit)? = null,
content: @Composable () -> Unit
) {
val swipeState = rememberSwipeableState(
initialValue = defaultState,
)
val scope = rememberCoroutineScope()
Box(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.swipeable(
state = swipeState,
anchors = mapOf(
0f to SwipeState.DEFAULT.value,
-Utils
.dp2px(128, context)
.toFloat() to SwipeState.SWIPED.value,
),
thresholds = { _, _ ->
FractionalThreshold(0.3f)
},
orientation = Orientation.Horizontal,
enabled = isEnabled
)
) {
Card(
modifier = Modifier
.align(Alignment.CenterEnd)
.width(96.dp)
.height(108.dp)
.padding(4.dp)
.clickable {
// onDelete(itemDataClass)
scope.launch {
swipeState.animateTo(0, tween(200, 0))
}
},
shape = RoundedCornerShape(8.dp)
) {
Icon(
painter = painterResource(id = R.drawable.ic_delete_white_24dp),
modifier = Modifier
.size(16.dp)
.padding(32.dp),
tint = colorResource(id = R.color.colorRed),
contentDescription = null,
)
}
Box(modifier = Modifier
.offset {
IntOffset(swipeState.offset.value.roundToInt(), 0)
}
.clickable {
onItemSelected?.invoke(itemDataClass)
if (swipeState.currentValue == SwipeState.SWIPED.value) {
scope.launch {
swipeState.animateTo(SwipeState.DEFAULT.value)
}
}
}
.fillMaxWidth()
.wrapContentHeight()
) {
content()
}
}
}
private enum class SwipeState(val value: Int) {
DEFAULT(0),
SWIPED(1);
}
您可以使用 swipeableState snapTo 函数来重置状态。
couroutineScope.launch {
swipeableState.snapTo(defaultState)
}