Skip to content

Instantly share code, notes, and snippets.

@rahulsainani
Created May 7, 2021 12:04
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 rahulsainani/b649b1608827085c1d568d464739c9a9 to your computer and use it in GitHub Desktop.
Save rahulsainani/b649b1608827085c1d568d464739c9a9 to your computer and use it in GitHub Desktop.
data class Feature(
@DrawableRes val iconResource: Int,
val contentDescription: String,
)
class FeaturesAdapter : ListAdapter<Feature, RecyclerView.ViewHolder>(FeatureDiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_feature_tile, parent, false)
return FeatureItemViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val itemViewHolder = holder as FeatureItemViewHolder
itemViewHolder.bind(getItem(position))
}
inner class FeatureItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bind(feature: Feature) {
with(itemView) {
imageFeature.setImageResource(feature.iconResource)
imageFeature.contentDescription = feature.contentDescription
}
}
}
}
class FeatureDiffCallback : DiffUtil.ItemCallback<Feature>() {
override fun areItemsTheSame(oldItem: Feature, newItem: Feature): Boolean =
oldItem.iconResource == newItem.iconResource
override fun areContentsTheSame(oldItem: Feature, newItem: Feature): Boolean =
oldItem == newItem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment