Я создал универсальный адаптер , который будет использоваться для любого типа данных и любого количества элементов (row_layout) в RecyclerView.
Я добавил к нему список щелчковGeneralViewHolder. Есть ли недостатки или проблемы в этом адаптере. И есть ли обратный вызов, который уменьшает recyclerView?
GenericAdapter.kt
class GenericAdapter<T>(protected val items: List<T>, val adapterBind: OnAdapterBind<T>)
: RecyclerView.Adapter<GeneralViewHolder<T>>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralViewHolder<T> =
GeneralViewHolder(parent, viewType) { position, mView ->
adapterBind.onItemClicked(position, mView)
}
override fun getItemCount(): Int = items.size
override fun getItemViewType(position: Int): Int = adapterBind.setLayoutId(position, items[position]);
override fun onBindViewHolder(holder: GeneralViewHolder<T>, position: Int) {
adapterBind.onBindData(holder.itemView, items[position])
}
}
GeneralViewHolder.kt
class GeneralViewHolder<T>(parent: ViewGroup, layoutId: Int,clicklistener : (pos: Int, aView: View) -> Unit) : RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(layoutId, parent, false)){
init {
itemView.setOnClickListener{
clicklistener.invoke(adapterPosition,itemView)
}
}
}
OnAdapterBind.class
public interface OnAdapterBind<T> {
///GeneralViewHolder setViewHolder(ViewGroup parent,int viewType);
void onBindData(View itemView, T data);
int setLayoutId(int position,T obj);
void onItemClicked(int position,View mView);
}
Для одного типа элемента назовите его как
val carList = listOf<Car>(Car("Moras", Color.BLACK),Car("honda", Color.BLUE),Car("audi", Color.BLACK),
Car("Moras", Color.BLACK),Car("honda", Color.BLUE),Car("audi", Color.BLACK),
Car("Moras", Color.BLACK),Car("honda", Color.BLUE),Car("audi", Color.BLACK))
recyclerView.adapter = GenericAdapter<Car>( carList, object : OnAdapterBind<Car> {
override fun onBindData(itemView: View?, data: Car?) {
itemView?.fruitTv?.text = data?.name
}
override fun setLayoutId(position: Int, obj: Car?): Int = R.layout.item_fruit
override fun onItemClicked(position: Int, mView: View?) {
Toast.makeText(this@FruitActivity,"Clicked -> " + position,Toast.LENGTH_LONG).show()
}
})
И для нескольких типов ViewType используйте ..
val list= listOf<Any>(Car("audi", Color.BLACK),Bus("Eicher",Color.BLUE),Bus("Benz",Color.BLACK),Car("Suzuki",Color.WHITE)
,Car("Moras", Color.BLACK),Car("honda", Color.BLUE),Car("audi", Color.BLACK))
recyclerView.adapter = GenericAdapter<Any>( list, object : OnAdapterBind<Any> {
override fun onBindData(itemView: View?, data: Any?) {
when(data){
is Car -> itemView?.fruitTv?.text = "Car Rasha"
is Bus -> itemView?.vegetableTv?.text = "Bus Bus"
}
}
override fun setLayoutId(position: Int, obj: Any?): Int {
when(obj){
is Car -> R.layout.item_fruit
is Bus -> R.layout.item_vegetable
}
return R.layout.item_fruit
}
override fun onItemClicked(position: Int, mView: View?) {
}
})