1

I am currently working on a list of expandable cards. I would like to close all other opened expandable cards except the currently selected.

The data I am working with is a Map<String, String>, however i don't know how to get reference to the list of items in the list to loop over it and close all others expect the current one. Any suggestions would be very helpful!

val size = viewModel.getQuestionsAndAnswers(groupName).size
            Column {
                var i = 0
                for(question in viewModel.getQuestionsAndAnswers(groupName)) {
                    ExpandableCard(
                        title =  question.key,
                        description = question.value,
                        position = i++,
                        onExpandableCardClicked = {
                            // question: how do I loop over all the items in expandable cards and close them.
                        }
                    )
                }
            }
ahmad
  • 2,149
  • 4
  • 21
  • 38

1 Answers1

2

You could have a state that informs the index of the currently opened card:

val selectedIndexState = rememberSaveable {
        mutableStateOf(-1)
    }

And then add a isExpanded argument to the ExpandableCard:

ExpandableCard(
    title = question.key,
    description = question.value,
    position = i++,
    isExpanded = selectedIndexState.value == i,
    onExpandableCardClicked = {
        selectedIndexState.value = i
    }
)

You may also consider using LazyColumn when working with lists like that:

val selectedIndexState = rememberSaveable {
    mutableStateOf(-1)
}
LazyColumn {
    itemsIndexed(
        items = viewModel.getQuestionsAndAnswers(groupName).toList()
    ) { index, question ->
        ExpandableCard(
            title = question.first,
            description = question.second,
            position = index,
            isSelected = selectedIndexState.value == index,
            onExpandableCardClicked = {
                selectedIndexState.value = index
            }
        )
    }
}
jpegoraro
  • 315
  • 2
  • 10