I have a LazyColumn
with a SnapFlingBehavior
. Everything works as expected when scrolling. However, on initial screen display as well as on screen rotation, the snapping is missing. How can I fix that, so I always have “snapped items”?
Should it make any difference in the solution: I don’t care about the missing snapping on initial screen display in my production use case, but only about the missing snapping after rotation.
Here is how it looks in correctly snapped state after some scrolling (yellow item centered):
Here it is after screen rotation, without any further scrolling (yellow item not centered):
And here is the initial screen state (no item centered):
This is my sample code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ScreenRotationSampleTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Sandbox(innerPadding)
}
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Sandbox(innerPadding: PaddingValues) {
val items = (1..200).toList()
val state = rememberLazyListState()
val flingBehavior = rememberSnapFlingBehavior(lazyListState = state)
LazyColumn(
state = state,
flingBehavior = flingBehavior,
modifier = Modifier
.fillMaxWidth()
.padding(innerPadding)
.height(400.dp)
) {
items(items, key = { item -> item }) { item ->
Canvas(modifier = Modifier
.height(300.dp)
.fillParentMaxWidth()) {
drawRect(
color = if (item % 2 == 0) {
Color.Black
} else {
Color.Yellow
}
)
}
}
}
}