-1

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.

Jaydip Kalkani
  • 2,493
  • 6
  • 24
  • 56

1 Answers1

3

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()
    }
  } 
}
pablisco
  • 14,027
  • 4
  • 48
  • 70
  • This solved my problem but i have another problem. I'm loading 5 ads and refreshing it continuously. problem is ad stops refreshing automatically. did you have any solution for this?? – Jaydip Kalkani Jan 17 '18 at 11:59
  • Ask another question. However, this doesn't seem like a normal behaviour for ads. Google will probably ban your account if you try to do that. – pablisco Jan 17 '18 at 15:35