Created
November 28, 2019 08:10
-
-
Save yaseen2591/c29d26b4d96b2615554928ee80c020e0 to your computer and use it in GitHub Desktop.
Example of Clean RecyclerViewAdapter with DiffUtil
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
class YourAdapter : ListAdapter<YourData, YourAdapter.ViewHolder>(YourDataDiffCallback()) { | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { | |
return ViewHolder.from(parent) | |
} | |
override fun onBindViewHolder(holder: ViewHolder, position: Int) { | |
val item = getItem(position) | |
holder.bind(item) | |
} | |
class ViewHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) { | |
val tv1: TextView = itemView.findViewById(R.id.tv_1) | |
val tv2: TextView = itemView.findViewById(R.id.tv_2) | |
val img1: ImageView = itemView.findViewById(R.id.img_1) | |
fun bind(item: YourData) { | |
val res = itemView.context.resources | |
tv1.text = "value1" | |
tv2.text = "value2" | |
img1.setImageResource(R.drawable.icon1) | |
} | |
companion object { | |
fun from(parent: ViewGroup): ViewHolder { | |
val layoutInflater = LayoutInflater.from(parent.context) | |
val view = layoutInflater.inflate(R.layout.list_item_, parent, false) | |
return ViewHolder(view) | |
} | |
} | |
} | |
class YourDataDiffCallback : DiffUtil.ItemCallback<YourData>() { | |
override fun areItemsTheSame(oldItem: YourData, newItem: YourData): Boolean { | |
return oldItem.uniqueId == newItem.uniqueId | |
} | |
override fun areContentsTheSame(oldItem: YourData, newItem: YourData): Boolean { | |
return oldItem == newItem | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment