https://kotlinlang.org logo
#compose
Title
# compose
k

K Merle

01/13/2022, 2:01 PM
How to prevent autoscroll on LazyColumn update if item index 0 is not visible?
Every new item that arrives as index 0 makes scroll move for that item height.
f

FunkyMuse

01/13/2022, 2:07 PM
Can you share the code?
k

K Merle

01/13/2022, 2:09 PM
I am unable to share code as it's company project. Should adding an new item to an index 0 not move scroll for that same height amount?
🤣 1
d

Dmitrii Smirnov

01/13/2022, 2:21 PM
and we are unable to answer questions like "I can't show you what I do but what am I doing wrong?"
k

K Merle

01/13/2022, 2:22 PM
I am asking a question, in a sense of, is something true or false. Sorry for not being able to share code.
Should adding an new item to an index 0 not move scroll for that same height amount?
d

Dmitrii Smirnov

01/13/2022, 2:26 PM
nobody ask you to violate NDA, you can easily share some part of it, replacing sensitive data with "something" - just like in previous question
generally it works like "i want some behavior from this code, and it works in another way plz help"
k

K Merle

01/13/2022, 2:30 PM
Lol, okay mate. Here it is.
Copy code
val lazyListState = rememberLazyListState()
    LazyColumn(
        state = lazyListState,
        reverseLayout = true,
        modifier = modifier
    ) {
        items(messages) { item ->
            MessageItem(item)
        }
}
1
a

Abhinav Suthar

01/13/2022, 3:50 PM
If you don't provide key then index is used as key. Now assume this nth item is focused and another item at index 0 is added. So now new nth item (previously (n-1)th item) is now focused. Try providing unique key per item(message) to items extention function
1
2
k

K Merle

01/13/2022, 4:22 PM
Thanks. This solved issue. I was using sealed class for my data and sealed class did not contain any properties. Passing an id to a sealed class and as a key inside
items(..,key={id})
solved an issue.
My first issue was solved with keys, but I've found different issue now. Scrolling to the end of list and Navigating from Screen A that contains this LazyColumn, to Screen B, and returning does not position scroll correctly. Using something like this solves the problem, but looks like hack. Am I missing something? Worth mentioning is that I am showing messages and pictures from the device storage with Coil.
Copy code
val itemOffset = rememberSaveable { mutableStateOf(0)}
    LaunchedEffect(itemOffset) {
        lazyListState.animateScrollToItem(lazyListState.firstVisibleItemIndex, itemOffset.value)
    }

    SideEffect {
        itemOffset.value = lazyListState.firstVisibleItemScrollOffset
    }
j

John Nichol

01/17/2022, 3:19 PM
For your second issue you need to hoist the LazyListState up so that it is remembered by whatever is composing Screen A, Otherwise a new LazyListState is going to be created and this contains the scroll position.
🙌 1
171 Views