Android Compose 实现 左滑删除
直接看源码
private enum class CardState {Collapsed /* 收缩 */, Expanded /* 展开的 */ // 哈哈哈,还能学点英文 (:
}
@Composable
private fun PersonCard(modifier: Modifier = Modifier, person: Person) {val density: Density = LocalDensity.current// 锚点val anchors: DraggableAnchors<CardState> = remember {DraggableAnchors<CardState> {CardState.Collapsed at 0FCardState.Expanded at -with(density){50.dp.toPx()}}}// 状态val state: AnchoredDraggableState<CardState> = remember {AnchoredDraggableState<CardState>(initialValue = CardState.Collapsed,anchors = anchors,)}// 渲染完成让删除按钮往右移动var intOffset: IntOffset by remember {mutableStateOf(value = IntOffset.Zero)}Box(modifier = Modifier.offset { IntOffset(state.offset.roundToInt(), 0) }.anchoredDraggable(state = state,orientation = Orientation.Horizontal).fillMaxWidth().height(height = 50.dp),contentAlignment = Alignment.CenterEnd // 必须是 2D Alignments.) {Box(modifier = Modifier.background(color = Color(0xFFFFCCBC)).fillMaxWidth().fillMaxHeight())Text(text = "删除",textAlign = TextAlign.Center,lineHeight = TextUnit(50F, TextUnitType.Sp),modifier = Modifier.fillMaxHeight().width(width = 50.dp).onSizeChanged {Log.i(TAG, "PersonCard -> Box2 onSizeChanged")intOffset = IntOffset(x = with(density) { 50.dp.toPx().toInt() }, y = 0)}.offset {Log.i(TAG, "PersonCard -> Box2 offset")intOffset}.background(color = Color(0xFFF8BBD0), shape = RoundedCornerShape(size = 10.dp)))}
}
Text本身是支持文本居中的,麻烦的是需要自己算行高,原理和css3居中文本一致。
效果如下:
