Created
December 15, 2017 19:27
-
-
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
This file contains hidden or 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
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