我可以以编程方式在onCreateViewHolder中添加admob吗?

时间:2017-05-23 23:53:06

标签: android android-studio admob

我想在我的RecyclerView中放置一个混蛋。所以我在ViewHolder

中添加了这个
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v;
    if (viewType == ad) {
        ad_act = 1;
        v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.adview, parent, false);

        AdView adView = new AdView(context);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544~3347511713");

    }

问题是横幅没有出现。我错过了什么?

我的adview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="0dp"
        android:id="@+id/ad_view"
        android:layout_marginBottom="1dp"
        android:layout_marginEnd="0dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp">

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
        android:layout_weight="0.33">
    </com.google.android.gms.ads.AdView>

    </android.support.v7.widget.CardView>

</RelativeLayout>

有什么问题?为什么我看不到广告?任何想法?

1 个答案:

答案 0 :(得分:1)

而不是像下面那样创建Admob对象:

AdView adView = new AdView(context);

您需要在Viewholder视图中找到您的广告视图,如下所示:

    AdView adView = (AdView) v .findViewById(R.id.adView);
    adView.setAdSize(AdSize.SMART_BANNER);
            adView.setAdUnitId("ca-app-pub-3940256099942544~3347511713");
  // Need to load your Ad using AdRequest.Builder() 
     AdRequest adRequest = new AdRequest.Builder().build();
                adView.loadAd(adRequest);