August 13, 2021

android BaseRecyclerView – genric recyclerview class with click listener

By lj007

Generic Recyclerview

I have created generic recyclerview , but why we need it? We need to know in activity when item is clicked or may be we need to create replaceAll method which is very common for all recyclerview. In that case this will be very usefull.

 
import androidx.recyclerview.widget.RecyclerView

abstract class BaseRvAdapter<V: baseviewholder<T>, T> : RecyclerView.Adapter<V>(), BaseHolderListener {

    open val list: ArrayList<T> = ArrayList()

    override fun onBindViewHolder(holder: V, position: Int) {
        holder.setListener<V>(this)
        holder.setItem(list[position])
    }

    override fun getItemCount(): Int {
        return list.size
    }

    fun replaceAll(newList: ArrayList<T>){
        this.list.clear()
        this.list.addAll(newList)
        notifyDataSetChanged()
    }

    fun addAll(newList: List<T>) {
        addAll(list.size, newList)
    }

    fun addAll(position: Int, newList: List<T>) {
        this.list.addAll(position, newList)
        notifyDataSetChanged()
    }

    fun removeAll(newList: List<T>) {
        this.list.removeAll(newList)
        notifyDataSetChanged()
    }
}
import android.view.View
import androidx.recyclerview.widget.RecyclerView

abstract class BaseViewHolder<T>(view: View) : RecyclerView.ViewHolder(view) {
    private var listener: BaseHolderListener? = null

    fun <V> setListener(listener: BaseHolderListener) : Unit {
        this.listener = listener
    }

    abstract fun setItem(t: T)

    init {
        itemView.setOnClickListener {
            listener?.holderItemClicked(adapterPosition)
        }
    }
}
    
  
import android.os.Bundle

interface BaseHolderListener {
    fun holderItemClicked(position: Int, bundle: Bundle? = null)
}

Conclusion

It is very handy, we don’t need to worry about onBindViewHolder in Adapter, we don’t need to create list for adapter, just we need to check for our multiple views, everything else may be in this class, or we can also update this class for everything else, which is general in case.
Feel free to share your views about this.
you can find it on githubalso: BaseRecyclerView