Hello and thanks in advance for considering my question. I would like to iterate through a list and be able to have the user click on an item to expand the item's card to show more content. The following code does show a list with separate cards for each item. However, when you click on a card all cards expand. I would like to be able to only expand the card that is selected. Here's my code:
@Composable
fun myList() {
var myList = listOf("Canada", "China", "USA", "Pakistan")
var expanded: Boolean by remember { mutableStateOf(false) }
LazyColumn(
Modifier
.fillMaxWidth()
.padding(10.dp)
)
{
items(myList) { countries ->
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 10.dp)
.clickable {
expanded = !expanded
},
shape = CardDefaults.elevatedShape,
colors = CardDefaults.elevatedCardColors(),
elevation = CardDefaults.elevatedCardElevation()
) {
Text(text = "$countries")
if (expanded) {
Text(text = "Content")
}
}
}
}
}
Any suggestions are very much appreciated!
I have tried the code and will help you. Can you try the code below:
@Composable
fun myList() {
val myList = listOf("Canada", "China", "USA", "Pakistan")
var expandedItems by remember { mutableStateOf(setOf<String>()) }
LazyColumn(
Modifier
.fillMaxWidth()
.padding(10.dp)
)
{
items(myList.size) { index ->
ElevatedCard(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 10.dp)
.clickable {
expandedItems = if (expandedItems.contains(myList[index])) {
expandedItems - myList[index]
} else {
expandedItems + myList[index]
}
},
shape = CardDefaults.elevatedShape,
colors = CardDefaults.elevatedCardColors(),
elevation = CardDefaults.elevatedCardElevation()
) {
Text(text = "$myList[index]")
if (expandedItems.contains(myList[index])) {
Text(text = "Content")
}
}
}
}
}