KO 외부 라이브러리 없이 RecyclerView.ItemDecoration만으로 Sticky Header를 구현한 샘플입니다.
EN A sample that implements a sticky header in RecyclerView using only RecyclerView.ItemDecoration, with no external library.
📖 Blog / 블로그 · Android Sticky Header RecyclerView (2021.06) KO
StickyHeaderItemDecoration전체 코드와 동작 설명이 글에 있습니다. EN The fullStickyHeaderItemDecorationcode and a walkthrough are in the post.
KO
onDrawOver에서 RecyclerView 위에 헤더를 덧그립니다.- 콜백(
SectionCallback)으로 현재 맨 위 아이템의 헤더 뷰와, 헤더 여부를 받습니다. - 다음 헤더가 닿으면
moveHeader로 밀어 올리고, 아니면drawHeader로 항상 맨 위에 고정해서 그립니다.
EN
onDrawOverdraws the header on top of the RecyclerView.- A
SectionCallbackprovides the header view for the top item and tells whether a position is a header. - When the next header touches it,
moveHeaderpushes it up; otherwisedrawHeaderpins it to the top.
interface SectionCallback {
fun isHeader(position: Int): Boolean
fun getHeaderLayoutView(list: RecyclerView, position: Int): View?
}recyclerView.addItemDecoration(
StickyHeaderItemDecoration(object : StickyHeaderItemDecoration.SectionCallback {
override fun isHeader(position: Int): Boolean = adapter.isHeader(position)
override fun getHeaderLayoutView(list: RecyclerView, position: Int): View? =
adapter.getHeaderView(list, position)
})
)KO
isHeader/getHeaderView는 예제 앱의SampleAdapter.kt에 구현되어 있고, 등록하는 코드는MainActivity.kt에 있습니다. ENisHeader/getHeaderVieware implemented in the sample'sSampleAdapter.kt, and the decoration is registered inMainActivity.kt.
| File | Description |
|---|---|
StickyHeaderItemDecoration.kt |
KO 핵심 ItemDecoration · EN The core ItemDecoration |
SampleAdapter.kt |
KO 헤더 여부와 헤더 뷰를 제공하는 어댑터 · EN Adapter that tells which items are headers and provides the header view |
MainActivity.kt |
KO RecyclerView에 ItemDecoration 등록 · EN Registers the ItemDecoration on the RecyclerView |
ListItemData.kt, SampleData.kt |
KO 목록 데이터 · EN List data |
- minSdk 21, compileSdk/targetSdk 30
- AndroidX
RecyclerView(KOcom.google.android.material:material:1.3.0을 통해 포함 · EN pulled in viacom.google.android.material:material:1.3.0)
- Sticky Header RecyclerView 응용하기
- Sticky Header Recyclerview using ItemDecoration without library
- RecyclerView - StickyHeader
- KO 안드로이드 UI·아키텍처 글은 Android 카테고리에서 볼 수 있습니다.
- EN More Android UI and architecture posts are in the Android category.
- Modern Android App Architecture
