HFRecyclerView
This is an Android library allowing to add Header and/or Footer in your RecyclerView in the simplest way possible.
USAGE
To add Header and/or Footer in your RecyclerView you need to add HFRecyclerView library in your project or you can also grab it from Gradle:
implementation 'com.mikhaellopez:hfrecyclerview:1.2.0'
KOTLIN
-
You need to create a custom
RecyclerView.Adapter
for your RecyclerView whichHFRecyclerView
with the object type of your choice (in my example, my object type isMyDataObject
). The first param inHFRecyclerView
constructor is a flag to determine if you want to add a header, and the last to add a footer.class ExampleAdapter : HFRecyclerView<MyDataObject>(true, true) { //... }
-
After that, override 3 methods and create 3 class which extend
RecyclerView.ViewHolder
in order to add the viewHolder for your Item, your Header and your Footer:class ExampleAdapter : HFRecyclerView<MyDataObject>(true, true) { //... //region Override Get ViewHolder override fun getItemView(inflater: LayoutInflater, parent: ViewGroup): RecyclerView.ViewHolder = ViewHolder.ItemViewHolder(inflater.inflate(R.layout.item_example, parent, false)) override fun getHeaderView(inflater: LayoutInflater, parent: ViewGroup): RecyclerView.ViewHolder = ViewHolder.HeaderViewHolder(inflater.inflate(R.layout.item_header, parent, false)) override fun getFooterView(inflater: LayoutInflater, parent: ViewGroup): RecyclerView.ViewHolder = ViewHolder.FooterViewHolder(inflater.inflate(R.layout.item_footer, parent, false)) //endregion //region ViewHolder Header and Footer sealed class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { class ItemViewHolder(view: View) : ViewHolder(view) { fun bind(item: String) { itemView.run { text.text = item } } } class HeaderViewHolder(view: View) : ViewHolder(view) class FooterViewHolder(view: View) : ViewHolder(view) } //endregion }
âšī¸ If you doesn't have a footer (same for header) you need to override
getFooterView
like this:override fun getFooterView(inflater: LayoutInflater, parent: ViewGroup): RecyclerView.ViewHolder? = null
-
You must override
onBindViewHolder
method to manage your views as you like:class ExampleAdapter : HFRecyclerView<MyDataObject>(true, true) { //... override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is ViewHolder.ItemViewHolder -> holder.bind(getItem(position)) is ViewHolder.HeaderViewHolder -> { } is ViewHolder.FooterViewHolder -> { } } } //... }
-
Finally, you can used your adapter and set yout data like this:
val adapter = ExampleAdapter() adapter.data = youtDataList recyclerview.adapter = adapter
âšī¸ You can see a full example here : ExampleAdapter and MainActivity
LICENCE
HFRecyclerView by Lopez Mikhael is licensed under a Apache License 2.0.