Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Kotlin - AdView adSize: val cannot be reassigned

Tags:

android

kotlin

MobileAds.initialize(this) { }

val adViewBottom = AdView(this)
adViewBottom.adSize = AdSize.BANNER

This worked before I updated the library, now I get

val cannot be reassigned

on

adViewBottom.adSize

changing val to var doesn't solve it


2 Answers

Admob 21.0.0 changed the way to set ad size directly. You can use the setAdSize method.

MobileAds.initialize(this) { }

val adViewBottom = AdView(this)
adViewBottom.setAdSize(AdSize.BANNER)
// adViewBottom.setAdSize(AdSize.FULL_BANNER)
// adViewBottom.setAdSize(... Anchored adaptive banner size ...)
like image 160
ocos Avatar answered Dec 04 '25 13:12

ocos


If you updated adMob dependency toimplementation 'com.google.android.gms:play-services-ads:21.1.0' And your intention is to use Anchored adaptive banner, most probably you will get that error. Here is the solution that works for me.

    MobileAds.initialize(this) {}

    adView = AdView(this)//instance of adView
    //get width of a device from window manager
    val display = windowManager.defaultDisplay
    val outMetrics = DisplayMetrics()
    display.getMetrics(outMetrics)

    val density = outMetrics.density

    var adWidthPixels = adContainerView.width.toFloat()
    if (adWidthPixels == 0f) {
        adWidthPixels = outMetrics.widthPixels.toFloat()
    }

    val adWidth = (adWidthPixels / density).toInt()
    
    adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth))

     
like image 29
Josi Avatar answered Dec 04 '25 12:12

Josi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!