Skip to content

Instantly share code, notes, and snippets.

@shibbirweb
Created November 23, 2022 09:44
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 shibbirweb/547c0e8e9a6c4b20641be020f048e00c to your computer and use it in GitHub Desktop.
Save shibbirweb/547c0e8e9a6c4b20641be020f048e00c to your computer and use it in GitHub Desktop.
Android Kotlin - Recycler View DiffUtil.ItemCallback
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
class QuestionBankListRecyclerViewAdapter(
private val onClickItem: ((questionBank: QuestionBank, position: Int) -> Unit)? = null
) :
RecyclerView.Adapter<QuestionBankListRecyclerViewAdapter.ViewBinder>() {
private val TAG by lazy { this::class.simpleName }
private val differCallback = object : DiffUtil.ItemCallback<QuestionBank>() {
override fun areItemsTheSame(oldItem: QuestionBank, newItem: QuestionBank): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: QuestionBank, newItem: QuestionBank): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, differCallback)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewBinder {
val binding =
RowQuestionBankBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewBinder(binding)
}
override fun onBindViewHolder(holder: ViewBinder, position: Int) {
val questionBank = differ.currentList[position]
holder.viewBinder.questionBank = questionBank
holder.viewBinder.executePendingBindings()
}
override fun getItemCount(): Int = differ.currentList.size
// color list for random background
private fun getColorList() = listOf(
R.color.orange_550,
R.color.green_550,
R.color.blue_550,
R.color.brown_550,
R.color.purple_550,
R.color.awesome_red_550
)
// set thumbnail color filter
private fun setThumbnailColorFilter(imageView: ImageView) {
try {
imageView.imageTintList =
ContextCompat.getColorStateList(
imageView.context,
getColorList().random()
)
} catch (e: Exception) {
e.printStackTrace()
}
}
inner class ViewBinder(val viewBinder: RowQuestionBankBinding) :
RecyclerView.ViewHolder(viewBinder.root) {
init {
onItemClickHandler()
setThumbnailColorFilter(viewBinder.thumbnailIv)
}
private fun onItemClickHandler() {
onClickItem ?: return
viewBinder.root.setOnClickListener {
val position = absoluteAdapterPosition
if (position == RecyclerView.NO_POSITION) return@setOnClickListener
val questionBank = differ.currentList[position]
onClickItem.invoke(questionBank, position)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment