Skip to content

Instantly share code, notes, and snippets.

@gabriel-TheCode
Last active March 10, 2022 16:03
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 gabriel-TheCode/9c761f8a33e2a40dfda5351c974494b7 to your computer and use it in GitHub Desktop.
Save gabriel-TheCode/9c761f8a33e2a40dfda5351c974494b7 to your computer and use it in GitHub Desktop.
class BlogAdapter(private val listener: BlogItemListener) : RecyclerView.Adapter<BlogViewHolder>() {
interface BlogItemListener {
fun onClickedBlog(blogTitle: CharSequence)
}
private val items = ArrayList<Blog>()
private lateinit var blog: Blog
fun setItems(items: ArrayList<Blog>) {
this.items.clear()
this.items.addAll(items)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlogViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_blog, parent, false)
return BlogViewHolder(view, listener)
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: BlogViewHolder, position: Int) {
val blog = items[position]
holder.textTitle.text = blog.title
holder.textDescription.text = blog.body
Glide.with(holder.itemLayout).load(blog.image)
.placeholder(R.drawable.placeholder)
.error(R.drawable.placeholder)
.apply(RequestOptions().centerCrop())
.into(holder.image)
}
}
class BlogViewHolder(itemView: View, private val listener: BlogAdapter.BlogItemListener) :
RecyclerView.ViewHolder(itemView),
View.OnClickListener {
val itemLayout: ConstraintLayout = itemView.blog_layout
val textTitle: TextView = itemView.text_title
val textDescription: TextView = itemView.text_description
val image: AppCompatImageView = itemView.image
init {
itemLayout.setOnClickListener(this)
}
override fun onClick(v: View?) {
listener.onClickedBlog(textTitle.text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment