Android RecyclerView Example

FuseAdView objects can be used in a RecyclerView in the same way as other views.

You may want to hold on to the banner view objects once created, as re-creating them will reload the banner (triggering a new banner ad request to the server).

For example:

Recycler View Holder

class AdViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    var adContainer: ConstraintLayout = view.findViewById(R.id.ad_container)
    var adView: FuseAdView? = null
    
    fun bind() {
        adView?.let {
            adContainer.addChild(it)
        }
    }
    
    fun unbind() {
        adView?.let {
            adContainer.removeView(it)
        }
    }
}

Recycler View Adapter

class MyViewAdapter(...) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    
    private var adViews = mutableMapOf<Int, FuseAdView>()

    private fun getAdView(context: Context, position: Int) : FuseAdView {
        val adView = adViews[position] ?: FuseAdView(context, code = "<zone_code>").also {
            it.setContraintLayoutFillParent()
            adViews[position] = it
        }

        return adView
    }    
    
    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int) : ViewHolder {
        if (viewType == BANNER_AD_TYPE) {
            val view = LayoutInflater.from(viewGroup.context)
                        .inflate(R.layout.ad_view_row, viewGroup, false)
            return AdViewHolder(view)
        } else {
            ...
        }
    }

    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
        if (viewHolder is AdViewHolder) {
            viewHolder.adView = getAdView(viewHolder.adContainer.context, position)
            viewHolder.bind()
        } else {
            ...
        }
    }
    
    override fun onViewRecycled(viewHolder: RecyclerView.ViewHolder) {
        super.onViewRecycled(viewHolder)
        if (viewHolder is AdViewHolder) {
            viewHolder.unbind()
        }
    }
    
    ...
}

fun View.setConstraintLayoutFillParent() {
    if (layoutParams != null) return
    
    layoutParams = ConstraintLayout.LayoutParams(0, 0).apply {
        startToStart = ConstraintLayout.LayoutParams.PARENT_ID
        endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
        topToTop = ConstraintLayout.LayoutParams.PARENT_ID
        bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
    }
}