2
\$\begingroup\$

I've just finished implementing a Generic RecyclerView adapter in my Android app, written in Kotlin.

BaseAdapter.kt:

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T>(
    private var dataList: ArrayList<T>
) : RecyclerView.Adapter<BaseViewHolder<T>>() {

    abstract fun setViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T>

    fun swapDataList(dataList: ArrayList<T>) {
        this.dataList = dataList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<T> {
        return setViewHolder(parent)
    }

    override fun onBindViewHolder(holder: BaseViewHolder<T>, position: Int) {
        holder.bind(dataList[position])
    }

    override fun getItemCount(): Int = dataList.size
}

BaseViewHolder.kt:

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer

abstract class BaseViewHolder<T>(override val containerView: View) : RecyclerView.ViewHolder(containerView),
    LayoutContainer {

    abstract fun bind(data: T)

}

All of my RecyclerView adapters extend BaseAdapter and have an inner ViewHolder class, which extends BaseViewHolder. I'm asking for suggestions and constructive criticism. What could I change to improve the overall performance of my class? Is there a better approach?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.