我已经创建了一个通用适配器,该适配器将用于RecyclerView中的任何类型的数据和任意数量的项目(行布局)。
我已将clicklistener添加到它的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的MultipleType使用。.
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?) {
}
})