-
-
Save nelletto/a739f90e03c54720349e61c5bb384131 to your computer and use it in GitHub Desktop.
SectionAdapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thanks for this fix :D I will update my version