Tobias Gronbach
03/15/2022, 1:35 PMsetContent {
val listState = rememberLazyListState()
val viewPortCenter = ((listState.layoutInfo.viewportEndOffset - listState.layoutInfo.viewportStartOffset) / 2) // <- as soon as I add this line infinite recomposition is triggered
....
}
Adam Powell
03/15/2022, 1:39 PMderivedStateOf {}
and ensure you only access that derived state object at drawing time, e.g. in a Modifier.drawBehind
or Modifier.graphicsLayer {}
blockTobias Gronbach
03/15/2022, 3:39 PMval listState = rememberLazyListState()
val viewPortCenter = ((listState.layoutInfo.viewportEndOffset - listState.layoutInfo.viewportStartOffset) / 2)
val centerItem = listState.layoutInfo.visibleItemsInfo.find { it.offset < viewPortCenter.value && (it.offset + it.size) > viewPortCenter.value }
val centeredBait = baits.find { it.adviceId == centerItem?.key } // I use adviceId as key in lazyColumn
var backgroundColorRes by remember { mutableStateOf(R.color.white) }
LaunchedEffect(centeredBait) {
backgroundColorRes = centeredBait?.adviceType?.colorRes() ?: R.color.white
}
Version 2 (nothing happens at all):
val viewPortCenter = derivedStateOf {
((listState.layoutInfo.viewportEndOffset - listState.layoutInfo.viewportStartOffset) / 2)
}
val centerItem by derivedStateOf {
listState.layoutInfo.visibleItemsInfo.find { it.offset < viewPortCenter.value && (it.offset + it.size) > viewPortCenter.value }
}
val centeredBait by derivedStateOf {
baits.find { it.adviceId == centerItem?.key }
}
LaunchedEffect(centeredBait) {
backgroundColorRes = centeredBait?.adviceType?.colorRes() ?: R.color.white
}
As you can see I'm changing the backgroundColor in LaunchedEffect and set it as background-color to my composable. I'm afraid maybe it's the wrong approach. I'm still getting used to compose.val backgroundColorRes by remember {
derivedStateOf {
val viewPortCenter =
((listState.layoutInfo.viewportEndOffset - listState.layoutInfo.viewportStartOffset) / 2)
val centerItem =
listState.layoutInfo.visibleItemsInfo.find { it.offset < viewPortCenter && (it.offset + it.size) > viewPortCenter }
val centeredBait = screenState.adviceBaits.find { bait -> bait.adviceId == centerItem?.key }
centeredBait?.adviceType?.colorRes() ?: R.color.white
}
}
val animateColor by animateColorAsState(colorResource(backgroundColorRes), animationSpec = tween(2000))