简体   繁体   中英

Android Kotlin - AdView adSize: val cannot be reassigned

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

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)

If you updated adMob dependency to implementation '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.adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth) *** here is the error, and replace it with the code below.
    adView.setAdSize(AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth))

     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM