Search code examples
androidlistviewandroid-recyclerviewadmobandroid-appcompat

Embedding ads within Recyclerview


I am trying to upgrade my app from listview to recyclerview. When I was using listview I had embedded ads within the listview using this tutorial.

I am not able to add it within recyclerview similarly. Any views on how this is to be done in a Recyclerview?

Currently in my listview the code is as below for loading ads:

    if ((position % k) == 0) {
      if (convertView instanceof AdView) {
        return convertView;
      } else {
        // Create a new AdView
        AdView adView = new AdView(activity, AdSize.BANNER,
                                   ADMOB_ID);

        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 - (int) Math.ceil(position / k) - 1,
          convertView, parent);
    }

This is how it should look:

ListView Items

Update: Refer this video from google, it gives the complete explanation


Solution

  • In your adapter, you first need to override getItemViewType, for example:

    @Override
    public int getItemViewType(int position) 
    {
        if (position % 5 == 0)
            return AD_TYPE; 
        return CONTENT_TYPE;
    }
    

    Then in onCreateViewHolder, inflate a different view according to the type. Something like this:

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) 
    {
        View v = null;
    
        if (viewType == AD_TYPE)
        {
            v = new AdView(activity, AdSize.BANNER, ADMOB_ID);
            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);
            v.setLayoutParams(params);
    
         AdRequest adRequest = new AdRequest.Builder().build();
            if (adRequest != null && v != null){
                v.loadAd(adRequest);
             }
        }
        else 
            v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_layout, viewGroup, false);
    
        RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(v);
        return viewHolder;
    }