【Kotlin/Android/AdMob】How to dynamically add banner ads! Generalizing adUnitId
What you will learn from this article
- How to dynamically add AdMob banner ads in Android Studio/Kotlin
index
[open]
\ アプリをリリースしました /
Environment
- Android Studio:Meerkat
- Kotlin:2.0.21
Recommended article: 【Kotlin/Android Studio】How to install AdMob! Implementing banner ads
I want to switch the banner ID between test and production
If you are implementing AdMob banner ads, you will need to switch the adUnitId(banner ID) between test and production. Doing this manually is a hassle, so I ran into a few issues when trying to implement it so that it would automatically switch for each environment, so I've summarized how to do it here.
adUnitId must be specified in XML, or an error will occur
When implementing AdMob banner ads, you need to add AdView to the XML side and specify adUnitId. I want this adUnitId to dynamically switch between test and production, but it is not possible to switch between environments on the XML side.
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
app:adSize="BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111"/>
So I tried to dynamically switch the adUnitId from the code, but an error occurred and it didn't work as expected.
adView.adUnitId = if (BuildConfig.DEBUG) {
BuildConfig.ADMOB_BANNER_ID_TEST
} else {
BuildConfig.ADMOB_BANNER_ID_PROD
}
How to dynamically switch IDs
Conclusion: To dynamically switch IDs, we were able to implement it by Dynamic addition of the banner ad view itself.
// Create and set AdView
val adView = AdView(this@MainActivity).apply {
setAdSize(AdSize.BANNER)
adUnitId = if (BuildConfig.DEBUG) {
BuildConfig.ADMOB_BANNER_ID_TEST
} else {
BuildConfig.ADMOB_BANNER_ID_PROD
}
// Load ad
loadAd(AdRequest.Builder().build())
}
// Specify layout parameters
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
gravity = Gravity.CENTER_HORIZONTAL
}
adView.layoutParams = layoutParams
// Add AdView to adViewLayout Add
binding.adViewLayout.addView(adView)
I am still learning, so if you find any mistakes or shortcomings, I would appreciate it if you could let me know.
Thank you for reading.






