Search code examples
androidadmobnative-ads

NativeExpressAdView in a CardView


<LinearLayout
    orientation="vertical">
...
   <android.support.v7.widget.CardView
        android:id="@+id/card_pitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        card_view:cardCornerRadius="0dp">

        <com.google.android.gms.ads.NativeExpressAdView
            android:id="@+id/adview_small_light"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:visibility="gone"
            ads:adSize="FULL_WIDTHx100"
            ads:adUnitId="xxx">
        </com.google.android.gms.ads.NativeExpressAdView>

    </android.support.v7.widget.CardView>
1-11 16:21:22.211 28899-28899/? W/Ads: Not enough space to show ad. Needs 411x100 dp, but only has 379x385 dp.
11-11 16:21:22.211 28899-28899/? W/Ads: Not enough space to show ad. Needs 411x100 dp, but only has 379x100 dp.
11-11 16:21:22.211 28899-28899/? W/Ads: Not enough space to show ad. Needs 411x100 dp, but only has 379x173 dp.
11-11 16:21:22.211 28899-28899/? W/Ads: Not enough space to show ad. Needs 411x100 dp, but only has 379x100 dp.

Ad does not show, the margin on the CardView has a problem with FULL_WIDTH. Is there a way to do this? Display the add with FULL_WIDTH used and some margin on the CardView. I have also tried putting padding and margin on the parent LinearLayout instead of margin on CardView with the same problem.


Solution

  • The FULL_WIDTH constant specifies that the ad should occupy the entire width of the device's screen. In your case, there isn't enough room for the ad since some of its ancestors introduce additional horizontal padding. To accomplish your goal, you can determine what the width should be at runtime. All you need to do is calculate the width of the device and subtract away the correct amount of padding. For example:

    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    width = displayMetrics.widthPixels / displayMetrics.density;
    adView.setAdSize(new AdSize(width - padding, 100));
    

    It's important to note that the values here are in dip (density-independent pixels) and not pixels.