在 Recyclerview 中嵌入广告

Embedding ads within Recyclerview

我正在尝试将我的应用程序从 listview 升级到 recyclerview。当我使用列表视图时,我使用 this tutorial 在列表视图中嵌入了广告。

我无法将它添加到 recyclerview 中。对如何在 Recyclerview 中完成此操作有任何看法吗?

目前在我的列表视图中加载广告的代码如下:

    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);
    }

它应该是这样的:

更新: 参考google中的this video,它给出了完整的解释

在您的适配器中,您首先需要覆盖 getItemViewType,例如:

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

然后在onCreateViewHolder中,根据类型inflate不同的view。像这样:

@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;
}

在您的 ArrayList 中,将空值添加到您要展示广告的位置

    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;
}

然后,

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = null;
    ViewHolder vh=null;
    if (viewType == AD_TYPE)
    {
        v=inflater.inflate(R.layout.adview_item, parent, false);
        vh=new AdviewHolder(v);

    }
    else {
        v = inflater.inflate(R.layout.cardview_items, parent, false);
        vh = new ContentViewHolder(v);
    }
    return vh;
}

这不会跳过任何项目,但会在所需位置插入广告。

如何添加广告列表项并且不要跳过内容项并且不要插入空项到内容列表?

private static final int LIST_AD_DELTA = 3;
private static final int CONTENT = 0;
private static final int AD = 1;

@Override
public int getItemViewType(int position) {
    if (position > 0 && position % LIST_AD_DELTA == 0) {
        return AD;
    }
    return CONTENT;
}

@Override
public BaseRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    if (viewType == CONTENT) {
        return new ContentRecyclerHolder(parent, layoutId) {
            @Override
            protected void onCardClick(CardView card) {
                fragmentManager.showPagerFragmentWithTransition(card.getContext(), getRealPosition(getAdapterPosition()));
            }
        };
    } else {
        return new AdRecyclerHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_ad, parent, false));
    }
}

@Override
public int getItemCount() {
    int additionalContent = 0;
    if (data.size() > 0 && LIST_AD_DELTA > 0 && data.size() > LIST_AD_DELTA) {
        additionalContent = data.size() / LIST_AD_DELTA;
    }
    return data.size() + additionalContent;
}

@Override
public void onBindViewHolder(BaseRecyclerHolder baseHolder, int position) {
    if (getItemViewType(position) == CONTENT) {
        ContentRecyclerHolder holder = (ContentRecyclerHolder) baseHolder;
        Content content = data.get(getRealPosition(position));
    } else {
        AdRecyclerHolder holder = (AdRecyclerHolder) baseHolder;
            AdRequest adRequest = new AdRequest.Builder().build();
            if (adRequest != null && holder.adView != null){
                holder.adView.loadAd(adRequest);
             }
    }
}

private int getRealPosition(int position) {
    if (LIST_AD_DELTA == 0) {
        return position;
    } else {
        return position - position / LIST_AD_DELTA;
    }
}

像这样通过数据绑定更容易加载广告:

@BindingAdapter({"bind:loadAds"})
public static void loadAds(AdView adView, boolean load) {
    AdRequest adRequest = new AdRequest.Builder().build();
    adView.loadAd(adRequest);
}

然后在 xml 中将此赞添加到 adView

        app:loadAds='@{true}'

像这样:

  <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        app:loadAds='@{true}'
        />

我正在使用 gson 转换器进行改造,需要在每 5 个项目后显示广告。通过使用以上所有答案,我得到了 item 的错误位置。所以我在 json 响应中每第 5 个元素插入自定义值。像这样

call.enqueue(new Callback<List<DataModel>>() {
            @Override
            public void onResponse(Call<List<DataModel>> call, Response<List<DataModel>> response) {

                if (response.body() != null) {

                    List<DataModel> list_Data = response.body();
                    List<DataModel> list_ad_Data = new ArrayList<>();

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

                        adapter = new HomeAdapter(getActivity(), list_ad_Data);

在我的适配器中。我已经根据

更改了视图类型
@Override
    public int getItemViewType(int position) {
        if (list_data.get(position) == null) {
            return AD;
        }
        return CONTENT;

    }

上面的答案中已经提到了更改视图类型。希望对以后的读者有所帮助。

我通过更改 onBindViewHolder() 中的一行来解决问题

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
    if(holder.getItemViewType()==POST_TYPE) {
        PostHolder postHolder=(PostHolder) holder;
        int bindingPosition=position - position / LIST_AD_DELTA;
        postHolder.textView.setText(List_Item.get(bindingPosition).getBtnText());
        postHolder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, DetailActivity.class);
                intent.putExtra("file", "file:///android_asset/" + List_Item.get(position).getHtmlFile());
                context.startActivity(intent);
            }
        });
    }else if(holder.getItemViewType()==AD_TYPE){

        
    }