[英]How to set multiple Recycle View to Single Adapter
如何將多個recycleview設置為單個適配器?
我正在創建一個應用程序,應用程序中有很多類別並創建多個適配器,model 和回收視圖使應用程序變得復雜。 很難為多個recycleview制作不同的適配器
我可以將多個recycleview 設置為一個適配器嗎? 通過使用 if 或 else 或 switch 案例如何做到這一點?
或者有什么替代方法??
我想這可能會對你有所幫助。
data class CategoryCheckList(var type: Int, val list: Any)
fun initData() {
val category1 = Category1()
val list1 = arrayOfList<CategoryCheckList>()
list1.add(CategoryCheckList(CATETORY_1), category1)
recyclerView.adapter = SingleListAdapter(context, list)
val category2 = Category2()
val list2 = arrayOfList<CategoryCheckList>()
list2.add(CategoryCheckList(CATETORY_2), category2)
recyelerView2.adapter = SingleListAdapter(context, list2)
}
class SingleListAdapter(
private val context: Context,
private val list: ArrayList<CategoryCheckList>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
CATETORY_1 -> {
val binding = ItemCategory1Binding.inflate(
LayoutInflater.from(parent.context), parent, false)
Category1ViewHolder(binding)
}
else -> {
val binding = ItemCategory2Binding.inflate(
LayoutInflater.from(parent.context), parent, false)
Category2ViewHolder(binding)
}
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is Category1ViewHolder -> {
list[position].let { holder.bind(it, position) }
}
is Category2ViewHolder -> {
list[position].let { holder.bind(it, position) }
}
else -> {
// default
list[position].let { (holder as Category1ViewHolder).bind(it, position) }
}
}
}
override fun getItemCount(): Int {
return list.size
}
override fun getItemViewType(position: Int): Int {
return list[position].type
}
}
class Category1ViewHolder(var binding: ItemCategory1Binding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(categoryCheckList: CategoryCheckList, position: Int) {
val nameHeader = categoryCheckList.list as Category1
// do something
}
}
class Category2ViewHolder(var binding: ItemCategory2Binding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(categoryCheckList: CategoryCheckList, position: Int) {
val checklist = categoryCheckList.list as Category2
// do something
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.