androidkotlinadmobadsgoogleads-mobile-unity

Multiple AdListener in android kotlin


I am making an app, for personal use, which has multiple banner ads on a single activity. I want to listen to onAdLoaded() events for all the ads. For this, I have to put AdListener for every ad. If I have ten ads, do I have to write the same code ten times?

So, my question is that is there any way to reduce this code like multiple buttons onClickListener like this? I have already tried to do this in the same way as onClickListener of buttons, but it doesn't work.

Some portion of my code:

    ad1.adListener = object : AdListener() {
        override fun onAdLoaded() {
            super.onAdLoaded()
            incrementCounter()
        }
    }

    ad2.adListener = object : AdListener() {
        override fun onAdLoaded() {
            super.onAdLoaded()
            incrementCounter()
        }
    }

    ad3.adListener = object : AdListener() {
        override fun onAdLoaded() {
            super.onAdLoaded()
            incrementCounter()
        }
    }

I have to repeat the same code for all of my ad units.That's make my code bulky and it's my problem.


Solution

  • You can group all your views in a list:

    val adViews = listOf(ad1, ad2, ...)
    

    And then, you can iterate over and set the listener:

    adViews.forEach { 
      it.adListener = object : AdListener() {
        override fun onAdLoaded() {
          super.onAdLoaded()
          incrementCounter()
        }
      } 
    }