This repository demonstrates how to integrate AdMob ads into a Jetpack Compose Android application. The project includes examples of displaying banner ads and interstitial ads within a Compose UI, utilizing Google's AdMob SDK.
- Banner Ads: Display banner ads within your Compose UI using
AdView. - Interstitial Ads: Load and show interstitial ads on specific user actions.
- LazyColumn Integration: Seamlessly integrate ads within a
LazyColumnlist.
Screen_recording_20240820_142938.mp4
-
Clone the repository:
git clone https://github.com/nisaefendioglu/jetpack-compose-admob.git
-
Open the project in Android Studio.
-
Sync the project with Gradle to install dependencies.
-
Initialize AdMob SDK: Before loading any ads, initialize the AdMob SDK in your
MainActivity:MobileAds.initialize(this) { // AdMob SDK is ready }
-
Display Banner Ads: Use the
AdmobBannercomposable to show banner ads in your UI:@Composable fun AdmobBanner(modifier: Modifier = Modifier) { AndroidView( modifier = Modifier.fillMaxWidth(), factory = { context -> AdView(context).apply { adSize = AdSize.BANNER adUnitId = "YOUR_AD_UNIT_ID" loadAd(AdRequest.Builder().build()) } } ) }
-
Show Interstitial Ads: Call the
showInterstialAd()method on user actions to display interstitial ads:private fun showInterstialAd() { InterstitialAd.load( this, "YOUR_AD_UNIT_ID", AdRequest.Builder().build(), object : InterstitialAdLoadCallback() { override fun onAdFailedToLoad(adError: LoadAdError) { // Handle error } override fun onAdLoaded(interstitialAd: InterstitialAd) { interstitialAd.show(this@MainActivity) } } ) }
-
LazyColumn with Ads: Integrate ads within a
LazyColumnusing theMyComposeListcomposable:@Composable fun MyComposeList(modifier: Modifier = Modifier, data: List<Any>) { LazyColumn(state = rememberLazyListState()) { items(data.size) { val item = data[it] if (item is DataItem) { MySimpleListItem(item = item) } else { AdmobBanner(modifier) } } } }