如何在回收站视图中放置 Admob Native Advanced Ads android?

How to place Admob Native Advanced Ads in recycler view android?

我想在 android 应用程序的回收站视图的每 3 个位置放置 admob 原生高级广告。

我想要Admob提供的模板。

https://github.com/googleads/googleads-mobile-android-native-templates

这里是xml原生广告的代码实现

<com.google.android.ads.nativetemplates.TemplateView
android:id="@+id/my_template"
<!-- this attribute determines which template is used. The other option is
@layout/gnt_medium_template_view -->
app:gnt_template_type="@layout/gnt_small_template_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

这是 AdmobJava 的代码实现

   MobileAds.initialize(this, "[_app-id_]");
   AdLoader adLoader = new AdLoader.Builder(this, "[_ad-unit-id_]")
 .forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
   @Override
   public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
      NativeTemplateStyle styles = new
          NativeTemplateStyle.Builder().withMainBackgroundColor(background).build();

      TemplateView template = findViewById(R.id.my_template);
      template.setStyles(styles);
      template.setNativeAd(unifiedNativeAd);

    }
 })
 .build();

  adLoader.loadAd(new AdRequest.Builder().build());
 }

RecyclerView 适配器Class:

public class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.MyViewHolder>{
private Context mContext;
private List<ArticleJson> articleList;
String titleoflist;

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView txtTitle,txtDesc,txtStatus,txtColor,txtAuthor;
    LinearLayout linearLayout;
    private ArticleJson m_articleJson;

    public MyViewHolder(View view) {
        super(view);
        txtTitle = view.findViewById(R.id.texViewArticleTitle)
        linearLayout = view.findViewById(R.id.article_linearlayout);
    }

    public void bindView(final ArticleJson articleJson){
        m_articleJson = articleJson;
        txtTitle.setText(articleJson.getmTitle());
        txtAuthor.setText(titleoflist);
    }
}

public ArticleAdapter(Context mContext, List<ArticleJson> articleList,String titleoflist) {
    this.mContext = mContext;
    this.articleList = articleList;
    this.titleoflist = titleoflist;
}

@NonNull
@Override
public ArticleAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View itemView = LayoutInflater.from(parent.getContext())
          .inflate(R.layout.list_item_article, parent, false);
   return new ArticleAdapter.MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ArticleAdapter.MyViewHolder holder, int position) {
final ArticleJson articleJson = articleList.get(position);
    holder.bindView(articleJson);
    holder.linearLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      //Toast
    }
});
}

@Override
public int getItemCount() {
    return articleList.size();
}
}

在您的文章列表中,每隔三个条目填写“空”值(如果需要,也可以填写“广告”字符串值)。

在您的适配器中为具有“空”值的列表条目设置 content_type = “AD_TYPE”:

    @Override
    public int getItemViewType(int position) {     
        if (yourList.get(position).getArticle().equals("null")) {
            ADPosition = position;
            return AD_TYPE;
        }
        return CONTENT_TYPE;
    }

并在您的 ViewHolderClass 中为 AD_TYPE 个条目设置 AD_Layout 并为 CONTENT_TYPE 个条目设置正常布局。

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == CONTENT_TYPE) {
    itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.normalLayoutRecyclerView,prent,false);
    return new MyViewHolder(itemView)
}
if (viewType == AD_TYPE) {
itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.ad_layout, parent, false);
}

return new MyViewHolder(itemView)

}

希望对您有所帮助。

GGK

首先创建广告容器 item_ads.xml 文件夹

    <com.google.android.ads.nativetemplates.TemplateView
android:id="@+id/my_template"
<!-- this attribute determines which template is used. The other option is
@layout/gnt_medium_template_view -->
app:gnt_template_type="@layout/gnt_small_template_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

secend in The adapter you must change the extends to

 extends RecyclerView.Adapter<RecyclerView.ViewHolder> 

现在您需要覆盖 4 个方法

public RecyclerView.ViewHolder onCreateViewHolder

public void onBindViewHolder

public int getItemCount()

public int getItemViewType

在 getItemViwType 方法中,我们定义了两种可能性

@Override
    public int getItemViewType(int position) {     
        if (AD_LOGIC_CONDITION)) {
            
            return AD_TYPE;
        }else{

        return CONTENT_TYPE; ///do not forget to initialize bouth of AD_TYPE and   CONTENT_TYPE
    }

然后我们创建两个视图持有者,一个用于您的内容,另一个用于我们的广告 我假设您知道如何创建您的视图持有者,所以我将只解释 AD 视图持有者

class adViewHolder extends RecyclerView.ViewHolder {
        TemplateView Adtemplate;

        public adViewHolder(@NonNull View itemView) {
            super(itemView);
            Adtemplate = itemView.findViewById(R.id.my_template);
        } 

现在我们 return 到 onCreateViewHolder 方法

public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        if (viewType == AD_TYPE) {
            adViewHolder madViewHolder = new adViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_ads, null, false));
            return madViewHolder;
        } else{
            YourViewHolder mYourViewHolder = new YourViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, null, false));
            return mYourViewHolder;
        }

现在我们转到 onBindViewHolder

 @Override
        public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == TYPE_CONTENT) {
                ///your data 
// AN EXAMPLE
                ((YourViewHolder) holder).textview.setText(data.getmtext());
                ((YourViewHolder) holder).Img.setImageResource(data.getmImg());
                ((YourViewHolder) holder).title.setText(data.getmName());
            } else if (getItemViewType(position) == TYPE_AD){
    
                final AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110")
                        .forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
                            @Override
                            public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
                                // Show the ad.
                                NativeTemplateStyle styles = new
                                        NativeTemplateStyle.Builder().build();
    
                                TemplateView template = ((adViewHolder) holder).Adtemplate;
                                template.setStyles(styles);
                                template.setNativeAd(unifiedNativeAd);
    
                            }
                        })
                        .withAdListener(new AdListener() {
                            @Override
                            public void onAdFailedToLoad(int errorCode) {
                                // Handle the failure by logging, altering the UI, and so on.
                            }
                        })
                        .withNativeAdOptions(new NativeAdOptions.Builder()
                                // Methods in the NativeAdOptions.Builder class can be
                                // used here to specify individual options settings.
                                .build())
                        .build();
                adLoader.loadAd(new AdRequest.Builder().build());
    
    
            }

MainActivity.java

    RecyclerView rvContacts = (RecyclerView) findViewById(R.id.rvContacts);

    // Initialize contacts
   contacts = Contact.createContactsList(20);

    // Create adapter passing in the sample user data
   ContactsAdapter adapter = new ContactsAdapter(contacts);

    //Build the native adapter from the current adapter
    AdmobNativeAdAdapter admobNativeAdAdapter=AdmobNativeAdAdapter.Builder.with(
            "ca-app-pub-3940256099942544/2247696110",//admob native ad id
            adapter,//current adapter
            "small"//Set the size "small", "medium" or "custom"
            ).adItemInterval(5)//Repeat interval
            .build();


    // Attach the new adapter to the recyclerview to populate items
    rvContacts.setAdapter(admobNativeAdAdapter);

    // Set layout manager to position the items
    rvContacts.setLayoutManager(new LinearLayoutManager(this));
}

更多阅读 RecyclerView-Native-ads-Example-Github