繁体   English   中英

如何在jetpack compose中保存可扩展卡组合state和滚动position

[英]How to save expandable card composable state and scrolling position in 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()
                }
            }
        }
    }
}

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

您应该将所有 state 保存在视图模型中。

可以保存滚动 position 的事件。

添加这个

rememberScrollableState{delta->
mViewModel.scrollState += delta
delta
}
)

如果您还没有,请创建一个名为 mViewModel.kt 的新文件,扩展视图模型 class。 添加一个名为 scrollState 的变量来存储 state 如上所述另外,添加一个 Boolean 值来存储消耗的 state ,如

var expanded by mutableStateOf (false)

试试看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM