简体   繁体   中英

How to save expandable card composable state and scrolling position in jetpack compose

I'm using custom expandable card as,

@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()
                }
            }
        }
    }
}

I'm using this composable to one of the screen containing list of data and its working. However, when I switch to other screen and back to expandable card screen then card state and scrolling position is changed. How can I save expandable card screen state and scrolling position so that it won't change.

You should save all the state in a viewmodel.

Event the scrolling position can be saved.

Add this

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

If you haven't already, create a new file named mViewModel.kt, extending the viewmodel class. Add a variable named scrollState to it to store the state as above Also, add a Boolean value to store the expended state, like

var expanded by mutableStateOf (false)

Try it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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