首页 > 解决方案 > 如何在jetpack compose中保存可扩展卡片组合状态和滚动位置

问题描述

我正在使用自定义可扩展卡,

@Composable
fun ExpandableCardComposable(
    isExpandable: Boolean = false,
    topContent: @Composable () -> Unit,
    buttomContent: @Composable () -> Unit
) {
    val transactionState = remember {
        MutableTransitionState(isExpandable)
            .apply {
                targetState = isExpandable
            }
    }
    val transaction = updateTransition( transactionState, label = "")
    Card(
        modifier = Modifier.padding(horizontal = Size.DOUBLE_SPACING),
        elevation = Size.Card.ELEVATION,
        shape = RoundedCornerShape(Size.Card.CORNER_RADIUS),
    ) {
        Column(modifier = Modifier.animateContentSize()) {
            Surface(elevation = Size.Card.ELEVATION) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable(onClick = { transactionState.targetState = !transaction.currentState })
                        .padding(horizontal = Size.DOUBLE_SPACING),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(modifier = Modifier.weight(1f)) {
                        topContent()
                    }
                    val iconId = if (transaction.currentState) R.drawable.close else R.drawable.expand
                    Image(
                        imageVector = ImageVector.vectorResource(id = iconId),
                        contentDescription = null
                    )
                }
            }

            if (transactionState.currentState) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth(),
                ) {
                    buttomContent()
                }
            }
        }
    }
}

我正在将此可组合用于包含数据列表及其工作的屏幕之一。但是,当我切换到其他屏幕并返回可扩展卡片屏幕时,卡片状态和滚动位置会发生变化。如何保存可扩展的卡片屏幕状态和滚动位置,使其不会改变。

标签: androidandroid-jetpack-composeandroid-jetpack-compose-listandroid-jetpack-compose-scaffoldandroid-jetpack-compose-surface

解决方案


https://developer.android.com/jetpack/compose/navigation

保存和恢复状态是在导航期间完成的。如果您正在使用导航组件,请参阅saveStaterestoreState


推荐阅读