Last active
March 12, 2021 20:14
-
-
Save GeorgCantor/fcd8788872ea647a643bacd995dd4398 to your computer and use it in GitHub Desktop.
This file contains 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 FeedAdapter( | |
private val pictures: List<Hit>, | |
) : ListAdapter<Hit, FeedAdapter.FeedViewHolder>(ItemDiffCallback()) { | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = FeedViewHolder( | |
LayoutInflater.from(parent.context).inflate(R.layout.item_feed, parent, false) | |
) | |
override fun onBindViewHolder(holder: FeedViewHolder, position: Int) { | |
val pic = pictures[position] | |
val images = listOf(pic.webformatURL, pic.webformatURL, pic.webformatURL) | |
with(holder) { | |
itemView.context.loadCircleImage(pic.userImageURL, icon) | |
name.text = pic.user | |
indices.text = "${viewPager.currentItem}/${images.size}" | |
viewPager.adapter = PagerAdapter(images) | |
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { | |
override fun onPageSelected(position: Int) { | |
setPageIndex(position + 1, images.size) | |
super.onPageSelected(position) | |
} | |
}) | |
fav.setOnClickListener { | |
fav.setImageResource( | |
when (fav.drawable.constantState) { | |
getDrawable(itemView.context, R.drawable.ic_favorite)?.constantState -> R.drawable.ic_favorite_red | |
getDrawable(itemView.context, R.drawable.ic_favorite_red)?.constantState -> R.drawable.ic_favorite | |
else -> R.drawable.ic_favorite | |
} | |
) | |
} | |
} | |
} | |
override fun getItemCount() = pictures.size | |
class FeedViewHolder(view: View) : RecyclerView.ViewHolder(view) { | |
val icon: ImageView = view.findViewById(R.id.icon) | |
val name: TextView = view.findViewById(R.id.name) | |
val indices: TextView = view.findViewById(R.id.pager_indices) | |
val viewPager: ViewPager2 = view.findViewById(R.id.view_pager) | |
val fav: ImageView = view.findViewById(R.id.fav) | |
fun setPageIndex(index: Int, allIndex: Int) { | |
indices.text = "$index/$allIndex" | |
} | |
} | |
class ItemDiffCallback : DiffUtil.ItemCallback<Hit>() { | |
override fun areItemsTheSame(old: Hit, new: Hit) = old == new | |
override fun areContentsTheSame(old: Hit, new: Hit) = old.id == new.id | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment