I want to implement an onClickListener for the followButton inside an item in a RecylerView. I haven't managed to find any tutorial/question which uses the way I followed and am completely clueless about the required approach in Kotlin. Here is the code for the adapter class where I have just managed to successfully implement an onItemClickListener for the itemView.
class adapterClass(private val exampleList : List<objectClass>, private val listener : onItemClickListener) : RecyclerView.Adapter<adapterClass.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false)
return ViewHolder(itemView)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentItem = exampleList[position]
val url: String = currentItem.imageResourceLink
val circularProgressDrawable = CircularProgressDrawable(holder.itemView.context)
circularProgressDrawable.strokeWidth = 10f
circularProgressDrawable.centerRadius = 100f
circularProgressDrawable.start()
GlideApp.with(holder.itemView.context).load(url).circleCrop().placeholder(circularProgressDrawable).error(R.drawable.error).fallback(R.drawable.fallback).transition(DrawableTransitionOptions.withCrossFade()).into(holder.imageView)
holder.textView1.text = currentItem.text1
holder.textView2.text = currentItem.text2
}
override fun getItemCount(): Int = exampleList.size
inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView), View.OnClickListener{
val imageView: ImageView = itemView.findViewById(R.id.imageView)
val textView1: TextView = itemView.findViewById<TextView>(R.id.textView)
val textView2: TextView = itemView.findViewById<TextView>(R.id.textView2)
val followButton: Button = itemView.findViewById(R.id.followButton)
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position : Int = adapterPosition
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(position)
}
}
}
interface onItemClickListener{
fun onItemClick(position:Int)
}
}
If possible, I would like the same way to be followed as is currently used(onClickListener in ViewHolder), to ensure reusability of this adapter throughout the app. Thanks.