androidadmobgoogle-dfpnative-adsmediaview

Google Ads MediaView not correctly resizing height to wrap_content when displaying image


I got an email from AdMob today saying:

Change to native ads policy: Native ads will require MediaView to render the video or main image asset. In an effort to help you deliver a better ad experience more easily, beginning October 29th, native ads will require MediaView to render the video or main image asset. Ad units not compliant by this date will stop serving ads, which could impact your ad revenue.

I tried this out in my Android app, removing the separate handling of images with ImageView and video with MediaView, but I have found that the MediaView is not resizing the view's height according to the height of the image it displays.

In this codelab example from Google, a fixed height and width for the MediaView are used. I cannot do this, as this screen is responsive to the screen size, which will change depending on the device. The fact that the image can be dynamically resized is one of the main benefits for using UnifiedNativeAds instead of predefined ads such as banners.

This is how I need to be displaying the MediaView, using match_parent for width and wrap_content for height.

<com.google.android.gms.ads.formats.MediaView
            android:id="@+id/ad_media"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:adjustViewBounds="true"
            android:scaleType="fitXY"/>

This is what I am currently getting from the above code

This is what I need and expect it to look like from using wrap_content

In the previous case where we were able to render the images separately using ImageView, the wrap_content value correctly sized the image.

Does anyone have a workaround for this? How can I follow the new Google requirements without hardcoding the MediaView's height?

My full code can be found here, in my demo app on github.


Solution

  • mediaView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
        @Override
        public void onChildViewAdded(View parent, View child) {
            if (child instanceof ImageView) {
                ImageView imageView = (ImageView) child;
                imageView.setAdjustViewBounds(true);
            }
        }
    
        @Override
        public void onChildViewRemoved(View parent, View child) {}
    });