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
}
}
}
}
)
}
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())
}
}
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With