Advertisement
DirzaAulia

PagingDataAdapter

Jun 22nd, 2022
746
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ArticleAdapter(
  2.   private val listener: OnItemClickListener
  3. ): PagingDataAdapter<ArticleContent, ArticleAdapter.ViewHolder>(ArticleDiffCallback()) {
  4.  
  5.   interface OnItemClickListener {
  6.     fun onItemClicked(data: ArticleContent)
  7.   }
  8.  
  9.   override fun onBindViewHolder(holder: ViewHolder, position: Int) {
  10.     val article = getItem(position)
  11.     article?.let { holder.bind(article) }
  12.   }
  13.  
  14.   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
  15.     return ViewHolder(
  16.       ItemCommonArticleBinding.inflate(
  17.         LayoutInflater.from(parent.context), parent, false
  18.       )
  19.     )
  20.   }
  21.  
  22.   inner class ViewHolder(
  23.     private val binding: ItemCommonArticleBinding
  24.   ): RecyclerView.ViewHolder(binding.root) {
  25.  
  26.     fun bind(item: ArticleContent) {
  27.       binding.run {
  28.         if (item.articleImages?.isNotEmpty() == true) {
  29.           val imageUrl = item.articleImages!![0].photo
  30.           val context = binding.root.context
  31.           image.loadNetworkImage(context, imageUrl)
  32.         }
  33.  
  34.         name.text = item.title
  35.         date.text = item.createdAt?.changeDateFormat(
  36.           "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
  37.           "dd MMM yyyy",
  38.           "UTC"
  39.         )
  40.         root.setOnClickListener {
  41.           listener.onItemClicked(item)
  42.         }
  43.       }
  44.     }
  45.   }
  46. }
  47.  
  48. private class ArticleDiffCallback: DiffUtil.ItemCallback<ArticleContent>() {
  49.   override fun areItemsTheSame(
  50.     oldItem: ArticleContent,
  51.     newItem: ArticleContent
  52.   ): Boolean {
  53.     return oldItem.id == newItem.id
  54.   }
  55.  
  56.   override fun areContentsTheSame(
  57.     oldItem: ArticleContent,
  58.     newItem: ArticleContent
  59.   ): Boolean {
  60.     return oldItem == newItem
  61.   }
  62. }
Advertisement
RAW Paste Data Copied
Advertisement