Android

Base RecyclerView realization

Here is small powerful base realization for easy RecyclerView usage

Base interface:

interface IBaseAdapter<T> {
    fun add(newItem: T)
    fun add(newItems: List<T>)
    fun add(newItem: T, position: Int)
    fun remove(position: Int)
    fun remove(item: T)
    fun clear()
}

And abstract realization:

abstract class BaseRecyclerAdapter<T>(private var items: MutableList<T>): RecyclerView.Adapter<BaseRecyclerAdapter<T>.BaseHolder>(), IBaseAdapter<T> {

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: BaseHolder, position: Int) = holder.bind(items[position])

    override fun add(newItem: T) {
        items.add(newItem)
        notifyItemInserted(items.size - 1)
    }

    override fun add(newItems: List<T>) {
        val position = items.size
        items.addAll(newItems)
        notifyItemRangeInserted(position, newItems.size)
    }

    override fun add(newItem: T, position: Int) {
        items.add(position, newItem)
        notifyItemInserted(position)
    }

    override fun remove(position: Int) {
        items.removeAt(position)
        notifyItemRemoved(position)
    }

    override fun remove(item: T) {
        val position = items.indexOf(item)
        items.removeAt(position)
        notifyItemRemoved(position)
    }

    override fun clear() {
        items.clear()
        notifyDataSetChanged()
    }

    abstract inner class BaseHolder(view: View): RecyclerView.ViewHolder(view) {
        abstract fun bind(item: T)
    }

}

Than we can use it:

class MyAdapter(var myItems: MutableList<Item> = mutableListOf()): BaseRecyclerAdapter<MyAdapter.Item>(myItems) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = MyHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_my, parent, false))

    inner class MyHolder(itemView: View): BaseHolder(itemView) {
        override fun bind(item: Item) = with(itemView) {
            findViewById<TextView>(R.id.item_my_line1).text = item.line1
            findViewById<TextView>(R.id.item_my_line2).text = item.line2
        }
    }

    data class Item(
            val line1: String,
            val line2: String
    )
}

Leave a reply

Your email address will not be published. Required fields are marked *

You may also like

More in:Android