Last active
November 10, 2019 18:45
-
-
Save xtenduke/cecd48c48e1902ff0a635477a09365fe to your computer and use it in GitHub Desktop.
Android Kotlin section recycler adapter
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
/* | |
* ------------------------------------------------------------ | |
* "THE BEERWARE LICENSE" (Revision 42): | |
* github.com/xtenduke wrote this code. As long as you retain this | |
* notice, you can do whatever you want with this stuff. If we | |
* meet someday, and you think this stuff is worth it, you can | |
* buy me a beer in return. | |
* ------------------------------------------------------------ | |
* | |
* This class is designed implement a 'similar' structure to TableView sections from iOS UIKit | |
*/ | |
abstract class SectionAdapter<VH : RecyclerView.ViewHolder> : RecyclerView.Adapter<VH>() { | |
/** | |
* Override getItemCount to instead call getItemCount(section: Int) | |
*/ | |
override fun getItemCount(): Int { | |
val sectionCount = getSectionCount() | |
var count = 0 | |
for(i in 0 until sectionCount) { | |
count += getItemCount(i) | |
} | |
return count | |
} | |
/** | |
* Get the item count per section | |
*/ | |
abstract fun getItemCount(section: Int): Int | |
/** | |
* Get the section count | |
*/ | |
abstract fun getSectionCount(): Int | |
/** | |
* Overridden to change the second parameter name from viewType to section | |
*/ | |
abstract override fun onCreateViewHolder(parent: ViewGroup, section: Int): VH | |
/** | |
* Abstract method for onBindViewHolder with section | |
*/ | |
abstract fun onBindViewHolder(holder: VH, position: Int, section: Int) | |
/** | |
* We need to turn our adapter position into a relative position based on the number | |
* of items in each section | |
*/ | |
override fun onBindViewHolder(holder: VH, position: Int) { | |
//derive section and position from position | |
//loop over all sections | |
var itemCount = 0 | |
var innerPosition = position | |
for(i in 0..getSectionCount()) { | |
itemCount += getItemCount(i) | |
if(position < itemCount) { | |
onBindViewHolder(holder, innerPosition, i) | |
return | |
} else { | |
innerPosition -= getItemCount(i) | |
} | |
} | |
} | |
/** | |
* Lookup Section based off adapter position | |
*/ | |
override fun getItemViewType(position: Int): Int { | |
var itemCount = 0 | |
for(i in 0..getSectionCount()) { | |
itemCount += getItemCount(i) | |
if (position < itemCount) { | |
return i | |
} | |
} | |
return super.getItemViewType(position) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment