Skip to content

LazySwappableRecyclerAdapter

Shanti Ranjan Das edited this page Apr 5, 2020 · 2 revisions

Here is a working sample of lazy loading recycler view.

AdapterClass for recyclerview

class AdapterLazyRecycler(recyclerView: RecyclerView) :
    LazySwappableRecyclerAdapter<CustomModel, CustomViewHolder, LazyLoadViewHolder>(recyclerView) {

    override fun onBindHolder(holder: CustomViewHolder, data: CustomModel, position: Int) {
        holder.bindViews(data)
    }

    override fun addLayoutForParsing(parent: ViewGroup, viewType: Int): CustomViewHolder {
        return CustomViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.layout_sample,
                parent,
                false
            )
        )
    }

    override fun onBindLazyLoadHolder(
        holder: LazyLoadViewHolder,
        visibility: Boolean,
        position: Int
    ) {
        holder.bindViews(visibility)
    }

    override fun addLazyLoadingLayoutParsing(parent: ViewGroup, viewType: Int): LazyLoadViewHolder {
        return LazyLoadViewHolder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.lazy_progress,
                parent,
                false
            )
        )
    }

    override fun onSwipeRightOrLeft(
        data: CustomModel,
        position: Int,
        swipeDirection: Int
    ): Boolean {
        //Return true if you want to delete it
        return false
    }

    override fun onDragFromPosition(
        fromData: CustomModel,
        fromPosition: Int,
        toData: CustomModel,
        toPosition: Int
    ): Boolean {
        //return false if you don't want to swipe position on drag
        return true
    }
}

Model class

class CustomModel(val firstName: String, val lastName: String)  

CustomViewHolder class

class CustomViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bindViews(customModel: CustomModel) {
        itemView.let {
            it.tv1.text = customModel.firstName
            it.tv2.text = customModel.lastName
        }
    }
}

This is just a simple adapter class. You just have to extend library's LazyRecyclerAdapter class. You can also call adapter.canSwapOrDrag(true) to enable swap or drag. Default is false.

Clone this wiki locally