Last active
February 3, 2023 12:47
-
-
Save axiel7/aad019c0ab37ea70e1d07f4320e55323 to your computer and use it in GitHub Desktop.
Android BaseAdapter for RecyclerView with ViewBinding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.LayoutInflater | |
import android.view.ViewGroup | |
import androidx.recyclerview.widget.RecyclerView | |
import androidx.viewbinding.ViewBinding | |
abstract class BaseAdapter<VB: ViewBinding, T> : RecyclerView.Adapter<BaseAdapter<VB, T>.ViewHolder>() { | |
protected abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB | |
protected var _list: List<T>? = listOf() | |
fun setData(list: List<T>) { | |
_list = list | |
notifyDataSetChanged() | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { | |
val binding = bindingInflater.invoke( | |
LayoutInflater.from(parent.context), | |
parent, | |
false) | |
return ViewHolder(binding) | |
} | |
override fun onBindViewHolder(holder: ViewHolder, position: Int) { | |
val item = _list?.get(position) | |
if (item != null) { | |
loadData(holder, position, item) | |
} | |
} | |
/** | |
* Called onBindViewHolder | |
*/ | |
protected abstract fun loadData(holder: ViewHolder, position: Int, item: T) | |
override fun getItemCount(): Int { | |
return _list?.size ?: 0 | |
} | |
inner class ViewHolder(val binding: VB) : RecyclerView.ViewHolder(binding.root) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment