이동식 저장소

[Compose] LazyList에서 아이템을 추가했을 때 스크롤 위치를 기억하는 방법 본문

Primary/Compose

[Compose] LazyList에서 아이템을 추가했을 때 스크롤 위치를 기억하는 방법

해스끼 2022. 12. 14. 16:25

LazyColumn에서 리스트 앞에 아이템을 추가하면 스크롤 위치가 위로 올라가 버린다.

스크롤 위치를 기억하고 싶다면 아이템의 key를 설정해야 한다. 공식 문서에는 다음과 같이 적혀 있다.

When you specify the key the scroll position will be maintained based on the key, which means if you add/remove items before the current visible item the item with the given key will be kept as the first visible one.

당연히 key는 유일해야 한다. 가장 쉬운 구현 방법은 아마도 hashCode()일 것이다.

val items: List<Item> = ...

LazyColumn(
    modifier = modifier
        .fillMaxWidth(),
    state = screenItemsState,
) {
    items(
        items = items,
        key = { item -> item.hashCode() }
    ) { ... }
}

리스트가 꽉 찬 후에만 스크롤 위치가 정상적으로 보존된다.

 

리스트가 꽉 차기 전에는 보존할 수 없는 건가? 내가 잘못 구현한 건가... 나중에 답을 알게 되면 수정하겠다.

'Primary > Compose' 카테고리의 다른 글

Preview 모드인지 확인하는 방법  (0) 2023.01.06
Brush로 다양한 색깔 효과 입히기  (0) 2023.01.04
[Relay] Slot 구현하기  (0) 2022.11.29
[Relay] Compose Theme에 접근하는 방법  (0) 2022.11.28
[Relay] Under the hood  (0) 2022.11.27
Comments