如何在Android Studio中的同一活动上显示两个Admob Native广告

j91ykkif  于 2023-05-01  发布在  Android
关注(0)|答案(2)|浏览(143)

我想在同一活动中使用2个Admob原生广告,但大小不同。我已经成功地发布了一个广告现在我想在同一活动中再显示一个本地广告。怎么做才合适
活动中的Admob实现

private void populateUnifiedNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView
            adView) {
        // Set the media view. Media content will be automatically populated in the media view once
        MediaView mediaView = adView.findViewById(R.id.ad_media);
        adView.setMediaView(mediaView);

        // Set other ad assets.
        adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
        adView.setBodyView(adView.findViewById(R.id.ad_body));
        adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
        adView.setIconView(adView.findViewById(R.id.ad_app_icon));
        adView.setPriceView(adView.findViewById(R.id.ad_price));
        adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
        adView.setStoreView(adView.findViewById(R.id.ad_store));
        adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));

        // The headline is guaranteed to be in every UnifiedNativeAd.
        ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());

        // These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
        // check before trying to display them.
        if (nativeAd.getBody() == null) {
            adView.getBodyView().setVisibility(View.INVISIBLE);
        } else {
            adView.getBodyView().setVisibility(View.VISIBLE);
            ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
        }

        if (nativeAd.getCallToAction() == null) {
            adView.getCallToActionView().setVisibility(View.INVISIBLE);
        } else {
            adView.getCallToActionView().setVisibility(View.VISIBLE);
            ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
        }

        if (nativeAd.getIcon() == null) {
            adView.getIconView().setVisibility(View.GONE);
        } else {
            ((ImageView) adView.getIconView()).setImageDrawable(
                    nativeAd.getIcon().getDrawable());
            adView.getIconView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getPrice() == null) {
            adView.getPriceView().setVisibility(View.INVISIBLE);
        } else {
            adView.getPriceView().setVisibility(View.VISIBLE);
            ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
        }

        if (nativeAd.getStore() == null) {
            adView.getStoreView().setVisibility(View.INVISIBLE);
        } else {
            adView.getStoreView().setVisibility(View.VISIBLE);
            ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
        }

        if (nativeAd.getStarRating() == null) {
            adView.getStarRatingView().setVisibility(View.INVISIBLE);
        } else {
            ((RatingBar) adView.getStarRatingView())
                    .setRating(nativeAd.getStarRating().floatValue());
            adView.getStarRatingView().setVisibility(View.VISIBLE);
        }

        if (nativeAd.getAdvertiser() == null) {
            adView.getAdvertiserView().setVisibility(View.INVISIBLE);
        } else {
            ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
            adView.getAdvertiserView().setVisibility(View.VISIBLE);
        }

        // This method tells the Google Mobile Ads SDK that you have finished populating your
        // native ad view with this native ad. The SDK will populate the adView's MediaView
        // with the media content from this native ad.
        adView.setNativeAd(nativeAd);

        // Get the video controller for the ad. One will always be provided, even if the ad doesn't
        // have a video asset.
        VideoController vc = nativeAd.getVideoController();

        // Updates the UI to say whether or not this ad has a video asset.
        if (vc.hasVideoContent()) {

            // Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
            // VideoController will call methods on this object when events occur in the video
            // lifecycle.
            vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
                @Override
                public void onVideoEnd() {
                    // Publishers should allow native ads to complete video playback before
                    // refreshing or replacing them with another ad in the same UI location.

                    super.onVideoEnd();
                }
            });
        } else {
        }
    }

    /**
     * Creates a request for a new native ad based on the boolean parameters and calls the
     * corresponding "populate" method when one is successfully returned.
     */
    private void refreshAd() {

        AdLoader.Builder builder = new AdLoader.Builder(this, getString(R.string.admob_native_advance));

        builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
            @Override
            public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
                // You must call destroy on old ads when you are done with them,
                // otherwise you will have a memory leak.
                if (nativeAd != null) {
                    nativeAd.destroy();
                }
//                nativeAd = unifiedNativeAd;
//
//
//                RelativeLayout relativeLayout =
//                        findViewById(R.id.fl_adplaceholder);
//                UnifiedNativeAdView adView = (UnifiedNativeAdView) getLayoutInflater()
//                        .inflate(R.layout.ad_unified, null);
//                populateUnifiedNativeAdView(unifiedNativeAd, adView);
//
//
//                relativeLayout.removeAllViews();
//                relativeLayout.addView(adView);

                NativeTemplateStyle styles = new
                        NativeTemplateStyle.Builder().build();
                TemplateView adView = findViewById(R.id.adview);
                adView.setVisibility(View.VISIBLE);
                adView.setStyles(styles);
                adView.setNativeAd(unifiedNativeAd);
            }

        });

        VideoOptions videoOptions = new VideoOptions.Builder()
                .build();

        NativeAdOptions adOptions = new NativeAdOptions.Builder()
                .setVideoOptions(videoOptions)
                .build();

        builder.withNativeAdOptions(adOptions);

        AdLoader adLoader = builder.withAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(int errorCode) {
                Log.w(HELPER_TAG, "onAdFailedToLoad: " + errorCode);
            }
        }).build();

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

第一个AdMob原生广告布局(成功实施)

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <com.google.android.gms.ads.formats.UnifiedNativeAdView
        android:id="@+id/native_ad_view"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:layout_centerInParent="true"
        android:background="@color/dark_bg"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="5dp"
            >
            <ImageView
                android:id="@+id/icon"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:layout_marginLeft="12dp"
                android:layout_marginTop="5dp"
                android:contentDescription="@null" />
            <TextView
                android:id="@+id/primary"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignTop="@id/icon"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="14dp"
                android:layout_marginTop="8dp"
                android:layout_marginRight="10dp"
                android:layout_toRightOf="@id/icon"
                android:lines="1"
                android:textColor="@color/white"
                android:textSize="@dimen/gnt_text_size_large"
                android:textStyle="bold" />
            <LinearLayout
                android:id="@+id/second_row"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/primary"
                android:layout_marginLeft="14dp"
                android:layout_marginTop="6dp"
                android:layout_marginRight="10dp"
                android:layout_toRightOf="@id/icon"
                android:orientation="horizontal">
                <RatingBar
                    android:id="@+id/rating_bar"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/gnt_ad_indicator_height"
                    android:lines="1"
                    android:numStars="0"
                    android:textColor="@color/white"
                    android:textSize="@dimen/gnt_text_size_small" />
                <TextView
                    android:id="@+id/secondary"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginStart="@dimen/gnt_no_margin"
                    android:layout_marginTop="@dimen/gnt_no_margin"
                    android:layout_marginEnd="@dimen/gnt_no_margin"
                    android:layout_marginBottom="@dimen/gnt_no_margin"
                    android:gravity="top"
                    android:lines="1"
                    android:textColor="@color/white"
                    android:textSize="@dimen/gnt_text_size_small" />
            </LinearLayout>
            <Button
                android:id="@+id/cta"
                android:layout_width="250dp"
                android:layout_height="0dp"
                android:layout_below="@id/icon"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="5dp"
                android:background="@drawable/main_ad_button"
                android:lines="1"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:textColor="@color/gnt_white"
                android:layout_alignParentRight="true" />
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/ad_text_background"
                >
                <TextView
                    android:id="@+id/ad_notification_view"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    android:text="Ad"
                    android:textColor="@color/white_color"
                    android:textSize="@dimen/gnt_ad_indicator_text_size"
                    android:textStyle="bold" />
            </RelativeLayout>
        </RelativeLayout>
    </com.google.android.gms.ads.formats.UnifiedNativeAdView>
</merge>

第二个AdMob布局文件(需要实现)

<com.google.android.gms.ads.formats.UnifiedNativeAdView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@color/dark_bg"
        android:minHeight="50dp"
        android:orientation="vertical">

        <TextView style="@style/AppTheme.AdAttribution"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="0dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/ad_app_icon"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:adjustViewBounds="true"
                    android:paddingBottom="5dp"
                    android:paddingEnd="5dp"
                    android:paddingRight="5dp"/>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/ad_headline"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textColor="#0000FF"
                        android:textSize="12sp"
                        android:textStyle="bold" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content">

                        <TextView
                            android:id="@+id/ad_advertiser"
                            android:layout_width="wrap_content"
                            android:layout_height="match_parent"
                            android:gravity="bottom"
                            android:textSize="13sp"
                            android:textStyle="bold"/>

                        <RatingBar
                            android:id="@+id/ad_stars"
                            style="?android:attr/ratingBarStyleSmall"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:isIndicator="true"
                            android:numStars="5"
                            android:stepSize="0.5" />
                    </LinearLayout>

                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/ad_body"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="20dp"
                    android:layout_marginEnd="20dp"
                    android:textSize="11sp" />

                <com.google.android.gms.ads.formats.MediaView
                    android:id="@+id/ad_media"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="200dp"
                    android:layout_height="105dp"
                    android:layout_marginTop="5dp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:orientation="horizontal"
                    android:paddingBottom="5dp"
                    android:paddingTop="5dp">

                    <TextView
                        android:id="@+id/ad_price"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dp"
                        android:paddingStart="5dp"
                        android:paddingRight="5dp"
                        android:paddingEnd="5dp"
                        android:textSize="12sp" />

                    <TextView
                        android:id="@+id/ad_store"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingLeft="5dp"
                        android:paddingStart="5dp"
                        android:paddingRight="5dp"
                        android:paddingEnd="5dp"
                        android:textSize="12sp" />

                    <Button
                        android:background="@drawable/main_ad_button"
                        android:id="@+id/ad_call_to_action"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:textSize="12sp" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</com.google.android.gms.ads.formats.UnifiedNativeAdView>
j0pj023g

j0pj023g1#

创建一个名为AdUtils的类,该类初始化并加载广告

public class AdUtils {

private Context context;
private FrameLayout frameLayout;
private int nativeAdLayout;
private String nativeAdsId;

private UnifiedNativeAd nativeAd;
private NativeAdListener nativeAdListener;

public void setNativeAdListener(NativeAdListener nativeAdListener){
    this.nativeAdListener= nativeAdListener;
}

 public AdUtils(Context context) {
    this.context = context;
}

public void loadNativeAd(FrameLayout frameLayout, int nativeAdLayout, String nativeAdsId) {
    this.nativeAdLayout = nativeAdLayout;
    this.frameLayout = frameLayout;
    this.nativeAdsId = nativeAdsId;
    this.nativeAd = loadNativeAd();
}

private UnifiedNativeAd loadNativeAd() {
    if ((nativeAdLayout == -1 && frameLayout == null)) {
        return null;
    }

    final UnifiedNativeAd[] nativeAd = {null};
    AdLoader.Builder builder;
    builder = new AdLoader.Builder(context, nativeAdsId);
    builder.forUnifiedNativeAd(unifiedNativeAd -> {

        if (nativeAd[0] != null) {
            nativeAd[0].destroy();
        }
        nativeAd[0] = unifiedNativeAd;
        UnifiedNativeAdView adView = (UnifiedNativeAdView) ((Activity) context).getLayoutInflater()
                .inflate(nativeAdLayout, null);
        populateNativeAdView(unifiedNativeAd, adView);
        frameLayout.removeAllViews();
        frameLayout.addView(adView);

        if (nativeAdListener != null) {
            nativeAdListener.onNativeAdLoaded();
        }
    });

    NativeAdOptions adOptions = new NativeAdOptions.Builder().build();

    builder.withNativeAdOptions(adOptions);

    AdLoader adLoader = builder.withAdListener(new AdListener() {
        @Override
        public void onAdFailedToLoad(int errorCode) {

            if (nativeAdListener != null) {
                nativeAdListener.onNativeAdError();
            }
        }

        @Override
        public void onAdOpened() {
            super.onAdOpened();
        }

        @Override
        public void onAdClicked() {
            super.onAdClicked();
        }
    }).build();

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

    return nativeAd[0];

}

private void populateNativeAdView(UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {

    MediaView mediaView = adView.findViewById(R.id.ad_media_main);
    adView.setMediaView(mediaView);
    adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
    adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
    adView.setIconView(adView.findViewById(R.id.ad_app_icon));

    ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());

    if (nativeAd.getCallToAction() == null) {
        adView.getCallToActionView().setVisibility(View.INVISIBLE);
    } else {
        adView.getCallToActionView().setVisibility(View.VISIBLE);
        ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
    }

    if (nativeAd.getIcon() == null) {
        adView.getIconView().setVisibility(View.INVISIBLE);
    } else {
        ((ImageView) adView.getIconView()).setImageDrawable(
                nativeAd.getIcon().getDrawable());
        adView.getIconView().setVisibility(View.VISIBLE);
    }

    adView.setNativeAd(nativeAd);
    VideoController vc = nativeAd.getVideoController();
    if (vc.hasVideoContent()) {

        vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
            @Override
            public void onVideoEnd() {
                super.onVideoEnd();
            }
        });
    }

}
public interface NativeAdListener {
    void onNativeAdLoaded();

    void onNativeAdError();
}
 }

Acitivity类布局文件中,添加两个Framelayouts

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:id="@+id/ad_container_one"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="220dp"
    android:id="@+id/ad_container_two"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/ad_container_one"
    app:layout_constraintVertical_bias="0.47000003" />

现在在你的Activity或片段中创建Adutils类的两个对象

AdUtils adUtilOne;
   AdUtils adUtilTwo;

现在,您必须通过将上下文传递给构造函数并将framelayout、adlayout和adId传递给load方法来初始化这两个对象。在activity中创建initAds方法,该方法调用初始化。

public void initAds(){
    String adIdOne="Your_ad_id";
    String adIdTwo="Your_ad_id";

    adUtilOne=  new AdUtils(this).loadNativeAd(frameLayoutAdOne,R.layout.ad_one, adIdOne);
    adUtilTwo= new AdUtils(this).loadNativeAd(frameLayoutAdOne,R.layout.ad_two, adIdTwo);

    adUtilOne.setNativeAdListener(new AdUtils.NativeAdListener() {
        @Override
        public void onNativeAdLoaded() {
            
        }

        @Override
        public void onNativeAdError() {
            frameLayoutAdOne.setVisibility(View.GONE);
        }
    });
    
    adUtilTwo.setNativeAdListener(new AdUtils.NativeAdListener() {
        @Override
        public void onNativeAdLoaded() {
            
        }

        @Override
        public void onNativeAdError() {
            frameLayoutAdOne.setVisibility(View.GONE);
        }
    });

}

并在findviewsby id完成后调用该方法。

wkyowqbh

wkyowqbh2#

这个问题有点老,但分享我的解决方案,因为一些人在未来寻找解决方案将受益于答案

注意:此方案不支持Recyclerview和Listview。

要在同一个Activity中显示两个原生广告,您需要在Activity xml中有两个FrameLayouts和两个原生广告xmls(如果您想显示不同大小的广告,否则一个就足够了)。
Admob现在提供了loadAds()方法,您可以一次请求最多5个广告。例如:

adLoader.loadAds(new AdRequest.Builder().build(), 5);

加载两个本地广告在这里是代码示例

int loadingCount = 0;

public void loadNativeAd(){

    AdLoader.Builder builder = new AdLoader.Builder(activity.getApplicationContext(),"YOUR_NATIVEAD_ID");

    builder.forNativeAd(
            new NativeAd.OnNativeAdLoadedListener() {
                @Override
                public void onNativeAdLoaded(NativeAd unifiedNativeAd) {
                    
                    // To count adload because loadAds() is equal to calling 
                    // loadAd() the number of ads you pass to loadAds() method.
                    loadingCount+=1; 

                    Log.d("NativeAdOnLoad", "Native Ad loaded "+loadingCount);

                    // If this callback occurs after the activity is destroyed
                    // You must call destroy on old ads when you are done with them,
                    // otherwise you will have a memory leak.
                    if (nativeAd != null) {
                        nativeAd.destroy();
                    }
                    nativeAd = unifiedNativeAd;
                    if (loadingCount == 1){

                        FrameLayout frameLayout = view.findViewById(R.id.fl_adplaceholder);

                        NativeAdView adView =
                                (NativeAdView) getLayoutInflater()
                                        .inflate(R.layout.ad_unified, null);
                        populateUnifiedNativeAdView(unifiedNativeAd, adView);
                        frameLayout.removeAllViews();
                        frameLayout.addView(adView);
                    }else if (loadingCount>1){
                        FrameLayout frameLayout = view.findViewById(R.id.fl_adplaceholder1);
                        loadingCount=0;
                       
                        // if you want to show ads in different sizes 
                        // pass your second layout here
                        NativeAdView adView =
                                (NativeAdView) getLayoutInflater()
                                        .inflate(R.layout.ad_unified, null);
                        populateUnifiedNativeAdView(unifiedNativeAd, adView);
                        frameLayout.removeAllViews();
                        frameLayout.addView(adView);
                    }

                }
            });

    VideoOptions videoOptions =
            new VideoOptions.Builder().setStartMuted(true).build();

    NativeAdOptions adOptions =
            new NativeAdOptions.Builder().setVideoOptions(videoOptions).build();

    builder.withNativeAdOptions(adOptions);

    AdLoader adLoader =
            builder
                    .withAdListener(
                            new AdListener() {
                                @Override
                                public void onAdFailedToLoad(LoadAdError loadAdError) {
                                    String error =
                                            String.format(
                                                    "domain: %s, code: %d, message: %s",
                                                    loadAdError.getDomain(),
                                                    loadAdError.getCode(),
                                                    loadAdError.getMessage());
                                    Toast.makeText(
                                                    activity,
                                                    "Failed to load native ad with error " + error,
                                                    Toast.LENGTH_SHORT)
                                            .show();
                                }
                            })
                    .build();

    adLoader.loadAds(new AdRequest.Builder().build(),2);

}

下面是populateUnifiedNativeAdView函数。

private void populateUnifiedNativeAdView(NativeAd nativeAd, NativeAdView adView) {
    // Set the media view.
    adView.setMediaView((MediaView) adView.findViewById(R.id.ad_media));

    // Set other ad assets.
    adView.setHeadlineView(adView.findViewById(R.id.ad_headline));
    adView.setBodyView(adView.findViewById(R.id.ad_body));
    adView.setCallToActionView(adView.findViewById(R.id.ad_call_to_action));
    adView.setIconView(adView.findViewById(R.id.ad_app_icon));
    adView.setPriceView(adView.findViewById(R.id.ad_price));
    adView.setStarRatingView(adView.findViewById(R.id.ad_stars));
    adView.setStoreView(adView.findViewById(R.id.ad_store));
    adView.setAdvertiserView(adView.findViewById(R.id.ad_advertiser));

    // The headline and mediaContent are guaranteed to be in every UnifiedNativeAd.
    ((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
    adView.getMediaView().setMediaContent(nativeAd.getMediaContent());

    // These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
    // check before trying to display them.
    if (nativeAd.getBody() == null) {
        adView.getBodyView().setVisibility(View.INVISIBLE);
    } else {
        adView.getBodyView().setVisibility(View.VISIBLE);
        ((TextView) adView.getBodyView()).setText(nativeAd.getBody());
    }

    if (nativeAd.getCallToAction() == null) {
        adView.getCallToActionView().setVisibility(View.INVISIBLE);
    } else {
        adView.getCallToActionView().setVisibility(View.VISIBLE);
        ((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
    }

    if (nativeAd.getIcon() == null) {
        adView.getIconView().setVisibility(View.GONE);
    } else {
        ((ImageView) adView.getIconView()).setImageDrawable(
                nativeAd.getIcon().getDrawable());
        adView.getIconView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getPrice() == null) {
        adView.getPriceView().setVisibility(View.INVISIBLE);
    } else {
        adView.getPriceView().setVisibility(View.VISIBLE);
        ((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
    }

    if (nativeAd.getStore() == null) {
        adView.getStoreView().setVisibility(View.INVISIBLE);
    } else {
        adView.getStoreView().setVisibility(View.VISIBLE);
        ((TextView) adView.getStoreView()).setText(nativeAd.getStore());
    }

    if (nativeAd.getStarRating() == null) {
        adView.getStarRatingView().setVisibility(View.INVISIBLE);
    } else {
        ((RatingBar) adView.getStarRatingView())
                .setRating(nativeAd.getStarRating().floatValue());
        adView.getStarRatingView().setVisibility(View.VISIBLE);
    }

    if (nativeAd.getAdvertiser() == null) {
        adView.getAdvertiserView().setVisibility(View.INVISIBLE);
    } else {
        ((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
        adView.getAdvertiserView().setVisibility(View.VISIBLE);
    }

    // This method tells the Google Mobile Ads SDK that you have finished populating your
    // native ad view with this native ad.
    adView.setNativeAd(nativeAd);

    // Get the video controller for the ad. One will always be provided, even if the ad doesn't
    // have a video asset.
    VideoController vc = nativeAd.getMediaContent().getVideoController();

    // Updates the UI to say whether or not this ad has a video asset.
    if (vc.hasVideoContent()) {

        // Create a new VideoLifecycleCallbacks object and pass it to the VideoController. The
        // VideoController will call methods on this object when events occur in the video
        // lifecycle.
        vc.setVideoLifecycleCallbacks(new VideoController.VideoLifecycleCallbacks() {
            @Override
            public void onVideoEnd() {
                // Publishers should allow native ads to complete video playback before
                // refreshing or replacing them with another ad in the same UI location.
                super.onVideoEnd();
            }
        });
    }
}

只需在您想要加载NativeAd的位置调用下面的函数

loadNativeAd();

相关问题