Last active
March 10, 2022 16:03
-
-
Save gabriel-TheCode/9c761f8a33e2a40dfda5351c974494b7 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 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