0

This is my code for RecyclerView:

public RecyclerGameAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = null;
if (viewType == AD_VIEW_TYPE) {}
else{
    v = LayoutInflater.from(parent.getContext()).inflate(
                            R.layout.recyclerview_games, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;    
}

I don't know how to declare the part that I´m showing the AdView in RecyclerAdapter.

Can you help me?

Sandip Armal Patil
  • 6,241
  • 21
  • 93
  • 160

1 Answers1

3

You would like to check the item type of the RecyclerView and then act accordingly. Use, the @Override method,

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

Then you can bind the content or the Ad to the item in onCreateViewHolder.

View view = null;

if (viewType == AD_TYPE)
{
    view = 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);
    view.setLayoutParams(params);
    view.loadAd(new AdRequest());
}
else{
    view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_layout, viewGroup, false);
}

RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(view);
return viewHolder;

This should do the job.

Also check out, this thread and this thread for more inputs. Similar questions as yours. The second one is exactly a copy of yours. Found it after answering your question.

Q2x13
  • 534
  • 1
  • 4
  • 14