I am trying to integrate AdMob banners in my Jetpack Compose application. However, I am facing an issue where the banner ads do not adjust correctly to the screen width in landscape mode. The container adjusts correctly, but the ad content does not scale properly.
Here is my Compose code:
private const val BANNER_AD_TEST_ID = "ca-app-pub-3940256099942544/6300978111"
class MainActivity : ComponentActivity() {
private var adView: AdView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MobileAds.initialize(this)
loadBannerAd()
setContent {
MyApplicationTheme {
Banner()
}
}
}
@Composable
private fun Banner() {
Box(modifier = Modifier.fillMaxWidth()) {
adView?.let { adView ->
AndroidView(
factory = { adView },
update = { loadBannerAd() },
modifier = Modifier
.fillMaxWidth()
.wrapContentHeight()
)
}
}
}
private fun loadBannerAd() {
// Destroy the old adView
this.adView?.destroy()
// Determine adSize
val displayMetrics = this.resources.displayMetrics
val screenWidth = (displayMetrics.widthPixels / displayMetrics.density).toInt()
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, screenWidth)
// Create new adView
val adView = AdView(this)
adView.adUnitId = BANNER_AD_TEST_ID
adView.setAdSize(adSize)
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
// Update adView
this.adView = adView
}
}
I have also referred to this Google AdMob Banner Example using Views, which adjusts perfectly (or at least much better) to the screen width.
Screenshots:
Here is a link to screenshots of both versions.
What I Need to Know:
- Why is my Compose implementation behaving differently from the Views example?
- How can I get the actual content of the ad container to adjust to the full width of the screen, similar to the Views example?
Additional Context:
- The banner ad is loaded, but it doesn’t resize properly when the orientation changes.
- I have verified that the adSize is calculated correctly.
Any help or guidance would be greatly appreciated!
Thanks!