Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper integration of Admob Banner ads in JetPack Compose

I am looking for correct integration of Admob Banner ads in my JetPack Compose View. In my case, I used to load Banner Ads in LazyColumn between various LazyColumn Items. But I am having a problem with combination of LazyColumn and Banner Ad. The banner Ad loads perfectly initially, but once I scroll away from my Ad view and the banner Ad becomes hidden, and then when I scroll back to my banner ad view, the ad view starts to reload again and the previously loaded ad gets killed.

Can anyone please guide me how do I prevent the Banner Ad View to get killed when I scroll away without causing it to reload again and again

The code that I am using is -

//MainView where I load ad 
@Composable
fun MainView(){
  
 LazyColumn{
   
   //other contents
   item {
    BannerAdView()
   }
   //other contents
  }
}


//BannerAdView
@Composable
fun BannerAdView() {

 AndroidView(
        modifier = Modifier.fillMaxWidth(),
        factory = { context ->
            AdView(context).apply {
                setAdSize(AdSize.BANNER)
                adUnitId = context.getString(R.string.adId)
                loadAd(AdRequest.Builder().build())
                adListener = object : AdListener() {
                    override fun onAdLoaded() {
                        isAdLoaded = true
                    }
                }
            }
        }
    )
 }
 
like image 843
Mayur Avatar asked Jan 18 '26 07:01

Mayur


1 Answers

Try this code, areAdsDisabled() will return true or false depending upon your usecase

@Composable
fun BannerAdView(adUnitId: String) {
    if (!areAdsDisabled()) {
        AndroidView(
            modifier = Modifier
                .fillMaxWidth(),
            factory = { context ->
                val adView = AdManagerAdView(context)
                adView.setAdSize(AdSize.BANNER)
                adView
            },
            update = { adView ->
                adView.adUnitId = adUnitId
                adView.doOnLayout {
                    adView.loadAd(AdRequest.Builder().build())
                }
            }
        )
    }
}
like image 115
algodextrous Avatar answered Jan 20 '26 20:01

algodextrous