0

I have a LazyColumn with items and advertisements. When I scroll down and up (see video) the Advertisement Composable is recomposed (good that is how it should work in compose), meaning that a new advertisement is loaded. The grey block with the text advertisement is a placeholder we use when the Ad is not loaded yet. Is it possible to keep the same advertisement in the LazyColumn? (the basic question here is: Can i have a Composable in a LazyColumn that will not be recomposed?)

enter image description here

I have tried a few things: adding keys to the items in the LazyColumn, remember the AdvertisementView (which is a AndroidView), but it's not working.

So my question is: Is this even possible with a LazyColumn in Compose? And if so, how can I do it?

Thank you!

Edit: added some code:

 LazyColumn() {
    items(list, key = {it.unitId}) { item ->
        when (item) {
            is ListItem.NormalItem -> NormalItem( )
            is ListItem.Advertisement -> AdvertisementAndroidView()
        }
    }
}

@Composable
fun AdvertisementAndroidView() {
    val context = LocalContext.current
    var isLoaded by remember { mutableStateOf(false) }

    val bannerView by remember { mutableStateOf(createAdView(context, advertisementData) {
    isLoaded = true })}

    Box() {
        if (!isLoaded) {
            AdvertisementPlaceHolder()
        } else {
            AndroidView( factory = {bannerView} )
        }
    }
}

private fun createAdView(context: Context, data: AdvertisementData, isLoaded: () -> Unit): AdManagerAdView {
  val view = AdManagerAdView(context)
  ...
  view.loadAd(adRequest)
  return view
}
Harrienak
  • 67
  • 9

1 Answers1

0

One way is that you can save your AdView in a viewmodel and reuse it whenever you want. Remember that you should remove that AdView from it's parent whenever parent should be destroyed.

mrzbn
  • 497
  • 1
  • 3
  • 15