So, I have this is my code for LazyColumn list
val selectedTongNumber = remember { mutableStateListOf<String>() }
LaunchedEffect(dataTongNumber.size) {
selectedTongNumber.addAll(dataTongNumber)
}
val tongNumberList = mutableListOf(TongNumber("012345"), TongNumber("014567"), TongNumber("024568"), TongNumber("034589"), TongNumber("124567"), TongNumber("134589"), TongNumber("234567"), TongNumber("234689"), TongNumber("234789"), TongNumber("245679"))
tongNumberList.forEach { tn ->
val availableSelected = selectedTongNumber.stream().filter { stn -> stn == tn.number }.collect(Collectors.toList())
if (availableSelected.isNotEmpty()) {
tn.isSelected = true
}
}
val scrollState = rememberLazyListState()
val coroutineScope = rememberCoroutineScope()
LazyColumn(
state = scrollState,
contentPadding = PaddingValues(12.dp),
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 150.dp)
) {
itemsIndexed(
items = tongNumberList.sortedByDescending { tn -> tn.isSelected },
key = { index, tn ->
tn.number
}
) { index, tongNumber ->
val isNumberChecked = remember { mutableStateOf(tongNumber.isSelected) }
Row(
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
.padding(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = isNumberChecked.value,
onCheckedChange = { isChecked ->
isNumberChecked.value = isChecked
tongNumber.isSelected = isChecked
if (isChecked) {
selectedTongNumber.add(tongNumber.number)
} else {
selectedTongNumber.remove(tongNumber.number)
}
coroutineScope.launch {
scrollState.animateScrollToItem(index = selectedTongNumber.size.minus(1))
}
}
)
Text(
text = tongNumber.number,
fontFamily = fonts,
fontSize = 14.sp,
color = blackPrimary
)
}
}
}
After I run the code, I saw the first item that is supposed to be in 'checked' state is not checked. And then, I scrolled down the list, scrolled it up again, and found out the supposed to in 'checked' state item is now checked like this.
I don't know where is my mistake and seems like I couldn't find any solution in the existing questions here, so I raised a question myself. Kindly help me to find the solution since I'm new in this Jetpack Compose. Thank you!