Search code examples
androidandroid-recyclerviewandroid-concatadapter

Setup margin/padding between different adapters in ConcatAdapter Android


Is it possible to set up spaces (margin/padding) between different adapters in ConcatAdapter? I have just a simple sample of code, like below, but according to the design I have to add margin exactly between different adapters (not holder items in one adapter). What is the best way to achieve that?

val firstAdapter: FirstAdapter = …
val secondAdapter: SecondAdapter = …
val thirdAdapter: ThirdAdapter = …
val concatAdapter = ConcatAdapter(firstAdapter, secondAdapter, thirdAdapter)

recyclerView.adapter = concatAdapter

ConcatAdapter


Solution

  • I managed to do something like this:

    class EmptySpaceAdapter(private val context: Context, private val height: Int) : RecyclerView.Adapter<BaseViewHolder<*>>() {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> {
        val view = View(context)
        view.layoutParams = ViewGroup.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, height)
        return EmptySpaceViewHolder(view)
    }
    
    override fun getItemCount() = 1
    
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    
    override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
        when (holder) {
            is EmptySpaceViewHolder -> holder.bind(true, position)
            else -> throw IllegalArgumentException("No view holder to show this data, did you forgot to add it to the onBindViewHolder?")
        }
    }
    
    inner class EmptySpaceViewHolder(itemView: View) : BaseViewHolder<Boolean>(itemView) {
        override fun bind(item: Boolean, position: Int) {
            Timber.d("onBind empty space")
        }
      }
    }
    

    ViewHolder:

    abstract class BaseViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
        abstract fun bind(item: T, position: Int)
    }