Over a million developers have joined DZone.

Embedding AdMob Adverts in Android ListViews

DZone's Guide to

Embedding AdMob Adverts in Android ListViews

· Mobile Zone ·
Free Resource

Whilst working on StackAnywhere (a new Android client for Stack Overflow and other Stack Exchange websites), I was trying to figure out how best to incorporate AdMob adverts in the UI so that I could make the app free to download. The stumbling block was that, with some space already taken up by the tabbed navigation, the additional space occupied by the adverts tended to make the user interface very cramped with little room for content. This was particularly problematic in landscape orientation since the adverts are the exact same dimensions as in portrait mode which means they take up proportionally more room vertically whilst wasting space horizontally.

StackAnywhere with an advert in a ListViewSince most of StackAnywhere’s activities feature ListViews, I eventually hit on the idea of embedding the adverts in the lists. This is not an entirely original idea, there are other apps that do something similar, but it has the advantage of displaying the advert prominently while also allowing the user to scroll it off screen and out of their way.

Implementing this solution is reasonably straightforward although there are a couple of minor pitfalls to avoid. The decorator pattern is an ideal approach to use since it allows you to add adverts to an existing list adapter without having to modify the code for that adapter. My naive first attempt fell foul of a ClassCastException when adding the AdView to the list, and I also had some focus issues to resolve. The code below is a simplified version of that used in StackAnywhere. The implementation simply adds one advert to the top of the list. You could easily modify this to show more adverts if you wish. For example, you could show an advert after every 10 items. The code assumes that you are using the new Google AdMob SDK (version 4.0.4 in this instance), rather than the old AdMob SDK.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}