我有一個帶有可擴展專案的 LazyColumn。當我單擊該專案時,他會展開或折疊,但我需要它,當我單擊關閉的元素時,它會打開,而串列中的其他元素會關閉。(打開的那個)。因此,首先我將專案的狀態從專案的可組合函式中的 remember 變數移動到 dataClass 元素串列。當我單擊專案時,他執行回呼以更改串列中它的元素的值,但它不會重新組合。
@Preview
@Composable
fun ExpandableCardList() {
val list = remember { mutableStateListOf(PointsCard(0),PointsCard(1),PointsCard(2),PointsCard(3),PointsCard(4),PointsCard(5))}
val state = rememberLazyListState()
Scaffold { paddingValues ->
LazyColumn(
state = state,
modifier = Modifier
.fillMaxWidth(),
contentPadding = paddingValues
) {
items(list, {it.key}) { item ->
ExpandableCard(
expanded = item.state,
state = {
bool -> item.state = bool
}
)
}
}
}
}
@Composable
fun ExpandableCard(expanded: Boolean, state: (bool:Boolean) -> Unit ){
Card(
Modifier
.fillMaxWidth()
.clickable { state(!expanded) }
.background(Color(Color.BLACK))
) {
Column(Modifier.background(Color(Color.BLACK)))
{
Box(
Modifier
.fillMaxWidth()
.height(54.dp)
.background(Color(Color.BLACK))
)
AnimatedVisibility(expanded) {
Box(
Modifier
.fillMaxWidth()
.padding(start = 10.dp)
.heightIn(56.dp, 300.dp)
.background(Color(Color.BLACK), shape = RoundedCornerShape(bottomStart = 8.dp)
)
)
}
}
}
}
data class PointsCard(
val key: Int = 0,
var state: Boolean = false
)
uj5u.com熱心網友回復:
如果你想要一個單一的選擇,你可能應該考慮在一個類中提升你的串列并通過串列的迭代器執行所有結構更改。
class CardListState {
val list = mutableStateListOf(PointsCard(0),PointsCard(1),PointsCard(2),PointsCard(3),PointsCard(4),PointsCard(5))
fun onSelected(isSelected: Boolean, item: PointsCard) {
val iterator = list.listIterator()
while (iterator.hasNext()) {
val obj = iterator.next()
if (obj.key != item.key) {
iterator.set(obj.copy(state = false))
} else {
iterator.set(obj.copy(state = isSelected))
}
}
}
}
@Composable
fun ExpandableCardList() {
val cardListState = remember { CardListState() }
val state = rememberLazyListState()
Scaffold { paddingValues ->
LazyColumn(
state = state,
modifier = Modifier
.fillMaxWidth(),
contentPadding = paddingValues
) {
items(cardListState.list, {it.key} ) { item ->
ExpandableCard(
expanded = item.state,
state = { bool ->
cardListState.onSelected(bool, item)
}
)
}
}
}
}
@Composable
fun ExpandableCard(
expanded: Boolean,
state: (bool:Boolean) -> Unit
) {
Card(
Modifier
.fillMaxWidth()
.clickable {
state(!expanded)
}
.background(Color.Black)
) {
Column(Modifier.background(Color.Black))
{
Box(
Modifier
.fillMaxWidth()
.height(54.dp)
.background(Color.Red)
)
AnimatedVisibility(expanded) {
Box(
Modifier
.fillMaxWidth()
.padding(start = 10.dp)
.heightIn(56.dp, 300.dp)
.background(Color.Green)
)
}
}
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/537866.html
標籤:安卓安卓布局android-jetpack-撰写惰性列组合重组
