Android
[Android] Recyclerview 클릭한 아이템을 가운데로 scroll 되게 하기
nurisis
2021. 8. 16. 22:47
반응형
Horizontal Recyclerview 에서 클릭한 아이템(selected item)을 가운데로 scroll 되게 하기.
사실 리스트가 많지 않으면 smoothScrollToPosition 등을 사용하면 되지만, 나의 경우 뿌려주는 리스트가 100개가 넘었기 때문에 smoothScrollToPosition 가 원하는대로 동작하지 않았다.
이와 관련해 구글링을 해보았지만, 원하는 방법을 찾지 못했다. 그래서 scrollToPositionWithOffset() 을 이용해 해결!!
// selectedPosition: Recyclerview adapter 를 통해 받아온 클릭된(선택된) 아이템의 position
private fun scrollSelectedItemToCenter(selectedPosition: Int) {
val layoutManager = dataBinding.horizontalRecyclerView.layoutManager as? LinearLayoutManager
// 가운데로 스크롤할 아이템이 왼쪽으로 부터 떨어진 거리.
// == 스크린너비/2 - 아이템의너비/2
val offset = (screenWidthPx / 2 - itemWidthPx / 2)
// [selectedPosition]번째 아이템을 왼쪽 가장자리에서 offset 만큼 떨어진 위치로 스크롤한다.
layoutManager?.scrollToPositionWithOffset(selectedPosition, offset)
}
아래는 위 코드에서의 offset 값을 그림으로 표현한 것.
scrollToPositionWithOffset(position, offset) 은 어떤 함수?
Scroll to the specified adapter position with the given offset from resolved layout start.
Layout의 start 지점으로 부터 offset 만큼 떨어진 위치로 position 번째 아이템을 스크롤한다.
![](https://t1.daumcdn.net/keditor/emoticon/friends1/large/026.gif)
반응형