Jetpack Compose

Integrating Banner Ads using Jetpack Compose

First, you need to create an instance of the banner ad. You can do this by initializing BannerView with the desired ad format. Here's how you can do it:

val banner = BannerView(this).apply { 
    banner(AdFormat.banner_320x50) 
} 

Also, you will need to create a delegate class to handle various ad events. This class should implement the BIDBannerViewDelegate interface:

class BannerViewDelegate : BIDBannerViewDelegate { 

     override fun adViewDidLoadAd(adView: BannerView, adInfo: AdInfo?) {		
          println("App - adViewDidLoadAd. AdView: $adView, AdInfo: $adInfo")
     }
 
     override fun adViewDidDisplayAd(adView: BannerView, adInfo: AdInfo?) {
          println("App - didDisplayAd. AdView: $adView, AdInfo: $adInfo")
     }

     override fun adViewDidFailToDisplayAd(adView: BannerView, adInfo: AdInfo?, errors: Error) {
          println("App - didFailToDisplayAd. AdView: $adView, Error:${errors.localizedMessage}")
     }

     override fun adViewClicked(adView: BannerView, adInfo: AdInfo?) {
          println("App - didClicked. AdView: $adView, AdInfo: $adInfo")
     }
     
     override fun allNetworksFailedToDisplayAd(adView: BannerView) {
         print("Banner - allNetworksFailedToDisplayAd")
     }
}

After creating your delegate class, set it as the delegate for the banner view:

val bannerShowDelegate = BannerViewDelegate() 
banner.setBannerViewDelegate(bannerShowDelegate)

Finally, incorporate the banner into your Composable UI. You can use AndroidView to integrate the traditional Android view with Jetpack Compose:

Box( 
    modifier = Modifier 
      .width(320.dp)
      .height(50.dp)
      .fillMaxWidth()
   ) {
       AndroidView(
           factory = { context -> 
               FrameLayout(context).apply { 
                   removeAllViews()
                   addView(banner) 
               } 
           }
      )
}

This code creates a Box with specified dimensions and uses AndroidView to host the banner. Make sure that the banner is properly initialized and the delegate is set before this Composable function is called in the UI.

Last updated