DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Embedding AdMob Adverts in Android ListViews

Embedding AdMob Adverts in Android ListViews

Dan Dyer user avatar by
Dan Dyer
·
May. 11, 11 · Interview
Like (0)
Save
Tweet
Share
15.55K Views

Join the DZone community and get the full member experience.

Join For Free

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 listview since 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.

import android.database.datasetobserver;
import android.view.view;
import android.view.viewgroup;
import android.widget.abslistview;
import android.widget.baseadapter;
import com.google.ads.adrequest;
import com.google.ads.adsize;
import com.google.ads.adview;
 
/**
 * list adapter decorator that inserts adverts into the list.
 * @author daniel dyer
 */
public class advertisingadapter extends baseadapter
{
    private static final string admob_publisher_id = "your_admob_id_here";
 
    private final activity activity;
    private final baseadapter delegate;
 
    public advertisingadapter(activity activity, baseadapter delegate)
    {
        this.activity = activity;
        this.delegate = delegate;
        delegate.registerdatasetobserver(new datasetobserver()
        {
            @override
            public void onchanged()
            {
                notifydatasetchanged();
            }
 
            @override
            public void oninvalidated()
            {
                notifydatasetinvalidated();
            }
        });
    }
 
    public int getcount()
    {
        return delegate.getcount() + 1;
    }
 
    public object getitem(int i)
    {
        return delegate.getitem(i - 1);
    }
 
    public long getitemid(int i)
    {
        return delegate.getitemid(i - 1);
    }
 
    public view getview(int position, view convertview, viewgroup parent)
    {
        if (position == 0)
        {
            if (convertview instanceof adview)
            {
                return convertview;
            }
            else
            {
                adview adview = new adview(activity, adsize.banner, admob_publisher_id);
                // disable focus for sub-views of the adview to avoid problems with
                // trackpad navigation of the list.
                for (int i = 0; i < adview.getchildcount(); i++)
                {
                    adview.getchildat(i).setfocusable(false);
                }
                adview.setfocusable(false);
                // default layout params have to be converted to listview compatible
                // params otherwise there will be a classcastexception.
                float density = activity.getresources().getdisplaymetrics().density;
                int height = math.round(adsize.banner.getheight() * density);
                abslistview.layoutparams params
                    = new abslistview.layoutparams(abslistview.layoutparams.fill_parent,
                                                   height);
                adview.setlayoutparams(params);
                adview.loadad(new adrequest());
                return adview;
            }
        }
        else
        {
            return delegate.getview(position - 1, convertview, parent);
        }
    }
 
    @override
    public int getviewtypecount()
    {
        return delegate.getviewtypecount() + 1;
    }
 
    @override
    public int getitemviewtype(int position)
    {
        return position == 0 ? delegate.getviewtypecount()
                             : delegate.getitemviewtype(position - 1);
    }
 
    @override
    public boolean areallitemsenabled()
    {
        return false;
    }
 
    @override
    public boolean isenabled(int position)
    {
        return position != 0 && delegate.isenabled(position - 1);
    }
}

from http://blog.uncommons.org/2011/05/09/embedding-admob-adverts-in-android-listviews

Android (robot)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Real-Time Analytics for IoT
  • Key Elements of Site Reliability Engineering (SRE)
  • gRPC on the Client Side
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: