Reputation: 8408
Is there a way to use mutiple View
types in a RecyclerView
without any items getting replaced?
For position
0 and every 4th position
in my RecyclerView
, I want the 2nd View
type to be shown without replacing what would've been in that position if the 1st View
type was there. I.e. show the 2nd View
type then the intended 1st View
type afterwards.
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder) {
is ViewHolderA -> {
MobileAds.initialize(mCtx) {}
mAdView = holder.itemView.findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
}
is ViewHolderB -> {
val product = my[holder.adapterPosition]
holder.tvTitle.text = product.itemTitle
}
}
}
override fun getItemViewType(position: Int): Int {
return if (position % 4 == 0) {
typeA
} else {
typeB
}
}
Expected result
Current result
Upvotes: 0
Views: 141
Reputation: 17248
Modify you onBindViewHolder
to bind items from position - position / 4 - 1
instead.
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder) {
is ViewHolderA -> {
MobileAds.initialize(mCtx) {}
mAdView = holder.itemView.findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
}
is ViewHolderB -> {
val positionToBind = position - position / 4 - 1
val product = my[positionToBind]
holder.tvTitle.text = product.itemTitle
}
}
}
This will return
position 0: -1 (ad so it doesnt apply)
position 1: 0 (item A)
position 2: 1 (item B)
position 3: 2 (item C)
position 4: 2 (ad so it doesnt apply)
position 5: 3 (item D)
etc.
Upvotes: 1