Как показать две нативные объявления Admob при одном и том же действии в студии android - PullRequest
0 голосов
/ 14 июля 2020

Я хочу использовать 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());
    }

1-й макет нативной рекламы 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>

2-й файл макета 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>

1 Ответ

0 голосов
/ 14 июля 2020

Создайте класс по имени 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" />

Теперь внутри вашей активности или фрагмента создайте два объекта класса Adutils

   AdUtils adUtilOne;
   AdUtils adUtilTwo;

теперь вы должны инициализировать оба объекта, передав контекст конструктору и, framelayout, adlayout и adId методу загрузки. Создайте метод 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.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...