在recyclerview中的广告视图替换项目

时间:2016-06-04 12:35:13

标签: android layout android-recyclerview ads

我使用此代码将广告放入recyclerview中。我的问题是广告项目取代了我的常规布局项目。 例如,如果我有10个项目的列表,我将获得项目5,并将项目9替换为adview。

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

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        AdView adview;
        ViewHolder holder;

       if (viewType == AD_TYPE) {
            adview = new AdView(mContext);
            adview.setAdSize(AdSize.BANNER);
            adview.setAdUnitId(mContext.getString(R.string.banner_ad_unit_id));

            float density = mContext.getResources().getDisplayMetrics().density;
            int height = Math.round(AdSize.BANNER.getHeight() * density);
            AbsListView.LayoutParams params = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, height);
            adview.setLayoutParams(params);

            AdRequest request = new AdRequest.Builder().build();
            adview.loadAd(request);
            holder = new ViewHolder(adview);

        } else{
            View view = inflater.inflate(R.layout.scores_list_item, parent, false);
            holder = new ViewHolder(view);
      }

        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        if(position % 5 != 3)  {
            cursor.moveToPosition(position);
            holder.home_name.setText(Utilies.getAdjustedTeamName(cursor.getString(COL_HOME)));
                holder.away_name.setText(Utilies.getAdjustedTeamName(cursor.getString(COL_AWAY)));

    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView home_name;
        public TextView away_name;

        public ViewHolder(View view) {
            super(view);
            if (!(itemView instanceof AdView)) {

                home_name = (TextView) view.findViewById(R.id.home_name);
                away_name = (TextView) view.findViewById(R.id.away_name);

                view.setOnClickListener(this);
            }
        }

1 个答案:

答案 0 :(得分:0)

在您的ArrayList中,在您想要adview的任何位置添加空值。

    for(int i=0;i<arr.size();i++){
       if(i%5==0)
       {
         alist.add(null);
       }
       alist.add(arr.get(i));
    }

然后在getItemViewType(),

  @Override
public int getItemViewType(int position) {
   if(qlist.get(position)==null)
       return AD_TYPE;
   return CONTENT_TYPE;
}

这将完成工作。