Skip to content

Instantly share code, notes, and snippets.

@raphaelbussa
Last active February 12, 2019 18:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save raphaelbussa/25191a8a081d56064f64d94ed83137b9 to your computer and use it in GitHub Desktop.
Save raphaelbussa/25191a8a081d56064f64d94ed83137b9 to your computer and use it in GitHub Desktop.
SectionAdapter
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class SectionAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val headerPositions: MutableMap<Int, Int> = mutableMapOf()
private val itemPositions: MutableMap<Int, Int> = mutableMapOf()
private val sectionItemPositions: MutableMap<Int, Int> = mutableMapOf()
private var listSize = 0
private var headerSize = 0
override fun onCreateViewHolder(parent: ViewGroup, type: Int): RecyclerView.ViewHolder {
if (type == 0) {
return onCreateSectionViewHolder(parent)
}
return onCreateItemViewHolder(parent)
}
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
if (headerPositions.contains(position)) {
//section
onBindSectionViewHolder(viewHolder, headerPositions[position] ?: 0)
}
val currentSection = sectionItemPositions[position]
val currentSectionPosition = itemPositions[position]
if (currentSection != null && currentSectionPosition != null) {
onBindItemViewHolder(viewHolder, currentSection, currentSectionPosition)
}
}
override fun getItemViewType(position: Int): Int {
if (headerPositions.contains(position)) {
//section
return 0
}
return 1
}
override fun getItemCount(): Int {
var size = 0
if(listSize != 0)
return listSize
for (sectionIndex in 0 until sectionCount()) {
if(!headerPositions.contains(size)) {
headerPositions[size] = headerSize
headerSize++
size++
for (itemIndex in 0 until itemCount(sectionIndex)) {
sectionItemPositions[size] = sectionIndex
itemPositions[size] = itemIndex
size++
}
}
}
listSize = size
return size
}
abstract fun sectionCount(): Int
abstract fun itemCount(section: Int): Int
abstract fun onCreateSectionViewHolder(viewGroup: ViewGroup): RecyclerView.ViewHolder
abstract fun onCreateItemViewHolder(viewGroup: ViewGroup): RecyclerView.ViewHolder
abstract fun onBindSectionViewHolder(viewHolder: RecyclerView.ViewHolder, sectionPosition: Int)
abstract fun onBindItemViewHolder(viewHolder: RecyclerView.ViewHolder, sectionPosition: Int, itemPosition: Int)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment