Search code examples
kotlinadapter

How to create custom Adapter with for 3 recycleViews


Hello All, i want to ask if i can add to my 3 recycle Views each recycle view hase interface to optimise my code i tried to add only 1 adapter for the 3 recycle View, as you can see my code below but i find my self stuck with this adapter, any 1 have idea how add custom adapter to adapt 3 recycle View? Thanx.

class CustomAdapter(private val contexte: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val context: Context = contexte

inner class FolderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}

inner class PagesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}

inner class CorpusViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    if (viewType == VIEW_TYPE_CORPUS)
        return CorpusViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.corpus_item_layout, parent, false)
        )
    if (viewType == VIEW_TYPE_FOLDER)
        return FolderViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.folder_item_layout, parent, false)
        )
    return PagesViewHolder(
        LayoutInflater.from(parent.context).inflate(
            R.layout.page_item_layout, parent, false
        )
    )
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    TODO("Not yet implemented")
}

override fun getItemCount(): Int {
    return 20
}


companion object {
    internal val VIEW_TYPE_CORPUS = 1
    internal val VIEW_TYPE_FOLDER = 2
    internal val VIEW_TYPE_PAGES = 2
}

Solution

  • Instead of doing this, I suggest you to use base class that takes layout id and initialize your common adapter with that.

    open class AdapterItem(val layoutId: Int)
    data class Corpus(val id: Int): AdapterItem(id)
    

    then init your adapter like CustomAdapter<AdapterItem>(...)

    in your adapter, override getView

    @Override
    fun getView(position: Int, convertView: View, parent: ViewGroup): View {
         val item = list[position]
         return if(converView != null){
              convertView
         } else {
              LayoutInflater.from(parent.context).inflate(item.layoutId, parent, false)
         }
    }