Skip to content

Instantly share code, notes, and snippets.

@pantos27
Created December 15, 2017 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pantos27/64e0712b88347ddeec9c5e2ed3b358e4 to your computer and use it in GitHub Desktop.
Save pantos27/64e0712b88347ddeec9c5e2ed3b358e4 to your computer and use it in GitHub Desktop.
DefaultViewHolder for a recycler view that handles most use cases needed. Props to this tutorial https://www.raywenderlich.com/172711/intermediate-recyclerview
package com.pantos27.someproject.recycler
import android.support.annotation.IdRes
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import java.util.*
class DefaultViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val viewMap: MutableMap<Int, View> = HashMap()
init {
findViewItems(itemView)
}
fun setText(@IdRes id: Int, text: String) {
val view = (viewMap[id] ?: throw IllegalArgumentException("View for $id not found")) as? TextView ?: throw IllegalArgumentException("View for $id is not a TextView")
view.text = text
}
fun getImage(@IdRes id: Int): ImageView {
return (viewMap[id] ?: throw IllegalArgumentException("View for $id not found")) as? ImageView ?: throw IllegalArgumentException("View for $id is not a ImageView")
}
private fun findViewItems(itemView: View) {
addToMap(itemView)
if (itemView is ViewGroup) {
val childCount = itemView.childCount
(0 until childCount)
.map { itemView.getChildAt(it) }
.forEach { findViewItems(it) }
}
}
private fun addToMap(itemView: View) {
if (itemView.id == View.NO_ID) {
itemView.id = View.generateViewId()
}
viewMap.put(itemView.id, itemView)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment