Does anyone have advice on how to keep a `LazyColu...
# compose
k
Does anyone have advice on how to keep a
LazyColumn
at a specific scroll amount, instead keeping an item/key visible, when inserting items? (i.e. sticking to the top of the list when inserting at zero)
That is, this code only shows the first N items, and then scrolls to maintain the top-most item continuously visible, pushing new items off the top of the screen
Copy code
@Composable
fun Example() {
  val state = rememberLazyListState()
  val items = remember { mutableStateListOf<String>() }
  
  LaunchedEffect(Unit) {
    while (isActive) {
      delay(1000)
      items.add(0, "Item ${items.size}")
    }
  }
    
  LazyColumn(
    state = state,
    modifier = Modifier.fillMaxSize(),
    contentPadding = PaddingValues(vertical = 32.dp),
  ) {
    items(items = items, key = { it }) { item ->
      Text(text = item, modifier = Modifier.padding(16.dp))
    }
  }
}
a
This might work in your case, you can try adding an empty
item
as a trick:
Copy code
LazyColumn(
        state = state,
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(vertical = 32.dp),
    ) {
        item {
            Spacer(Modifier.fillMaxWidth())
        }
        items(items = items, key = { it }) { item ->
            Text(text = item, modifier = Modifier.padding(16.dp))
        }
    }
It doesn’t change anything visually in this case, but it does change the behavior: When you’re scrolled all the way to the top, the “currently visible item” is the
Spacer
, so adding new items below it keeps the
Spacer
at the top.
I’m selfishly curious if you had success with that, if that was the behavior you were looking for 😄
k
It is the behavior I wanted. But it doesn’t work for LazyGrid, and it would be better if there was more than a 1px threshold
a
For
LazyGrid
you might be able to make the item use the max span? And you might be able to mess around with the height of the spacer to change behavior a bit, but yeah not super configurable otherwise