Lorsqu'une annonce native est chargée, GMA Next-Gen SDK appelle l'écouteur pour le format d'annonce correspondant. Votre application est alors responsable de l'affichage de l'annonce, mais elle n'est pas nécessairement obligée de le faire immédiatement. Pour faciliter l'affichage des formats d'annonces définis par le système, le SDK propose des ressources utiles, comme décrit ci-dessous.
. Consultez également les Règles et consignes relatives aux annonces natives pour savoir comment afficher vos annonces natives.Définir la classe NativeAdView
Définissez une NativeAdView classe. Cette classe est une
ViewGroup
classe et constitue le conteneur de niveau supérieur pour une NativeAdView classe. Chaque vue d'annonce native contient des composants d'annonce native, tels que l'élément de vue MediaView ou l'élément de vue Title, qui doivent être un enfant de l'objet NativeAdView.
Mise en page XML
Ajoutez un XML NativeAdView à votre projet :
<com.google.android.libraries.ads.mobile.sdk.nativead.NativeAdView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical">
<LinearLayout
android:orientation="horizontal">
<ImageView
android:id="@+id/ad_app_icon" />
<TextView
android:id="@+id/ad_headline" />
</LinearLayout>
<!--Add remaining assets such as the image and media view.-->
</LinearLayout>
</com.google.android.libraries.ads.mobile.sdk.nativead.NativeAdView>
Jetpack Compose
- Incluez le dossier JetpackCompose Utilities. Ce dossier inclut des assistants pour composer l'objet
NativeAdViewet les composants.
Composez un NativeAdView :
import com.google.android.gms.compose_util.NativeAdAttribution
import com.google.android.gms.compose_util.NativeAdView
@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
NativeAdView {
// Display the ad attribution.
NativeAdAttribution(text = context.getString("Ad"))
// Add remaining assets such as the image and media view.
}
}
Gérer l'annonce native chargée
Lorsqu'une annonce native est chargée, gérez l'événement de rappel, gonflez la vue d'annonce native et ajoutez-la à la hiérarchie des vues :
Kotlin
// Build an ad request with native ad options to customize the ad.
val adTypes = listOf(NativeAd.NativeAdType.NATIVE)
val adRequest = NativeAdRequest
.Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
.build()
val adCallback =
object : NativeAdLoaderCallback {
override fun onNativeAdLoaded(nativeAd: NativeAd) {
activity?.runOnUiThread {
val nativeAdBinding = NativeAdBinding.inflate(layoutInflater)
val adView = nativeAdBinding.root
val frameLayout = myActivityLayout.nativeAdPlaceholder
// Populate and register the native ad asset views.
displayNativeAd(nativeAd, nativeAdBinding)
// Remove all old ad views and add the new native ad
// view to the view hierarchy.
frameLayout.removeAllViews()
frameLayout.addView(adView)
}
}
}
// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback)
Java
// Build an ad request with native ad options to customize the ad.
List<NativeAd.NativeAdType> adTypes = Arrays.asList(NativeAd.NativeAdType.NATIVE);
NativeAdRequest adRequest = new NativeAdRequest
.Builder("ca-app-pub-3940256099942544/2247696110", adTypes)
.build();
NativeAdLoaderCallback adCallback = new NativeAdLoaderCallback() {
@Override
public void onNativeAdLoaded(NativeAd nativeAd) {
if (getActivity() != null) {
getActivity()
.runOnUiThread(() -> {
// Inflate the native ad view and add it to the view hierarchy.
NativeAdBinding nativeAdBinding = NativeAdBinding.inflate(getLayoutInflater());
NativeAdView adView = (NativeAdView) nativeAdBinding.getRoot();
FrameLayout frameLayout = myActivityLayout.nativeAdPlaceholder;
// Populate and register the native ad asset views.
displayNativeAd(nativeAd, nativeAdBinding);
// Remove all old ad views and add the new native ad
// view to the view hierarchy.
frameLayout.removeAllViews();
frameLayout.addView(adView);
});
}
}
};
// Load the native ad with our request and callback.
NativeAdLoader.load(adRequest, adCallback);
Notez que tous les composants d'une annonce native donnée doivent être affichés dans la mise en page NativeAdView. GMA Next-Gen SDK tente de consigner un avertissement lorsque
des composants natifs sont affichés en dehors d'une mise en page de vue d'annonce native.
Les classes de vue d'annonce fournissent également des méthodes permettant d'enregistrer la vue utilisée pour chaque composant individuel, ainsi qu'une méthode permettant d'enregistrer l'objet NativeAd lui-même.
L'enregistrement des vues de cette manière permet au SDK de gérer automatiquement des tâches telles que :
- l'enregistrement des clics ;
- l'enregistrement des impressions lorsque le premier pixel est visible à l'écran ;
- l'affichage de la superposition "Choisir sa pub".
Afficher l'annonce native
L'exemple suivant montre comment afficher une annonce native :
Kotlin
private fun displayNativeAd(nativeAd: NativeAd, nativeAdBinding : NativeAdBinding) {
// Set the native ad view elements.
val nativeAdView = nativeAdBinding.root
nativeAdView.advertiserView = nativeAdBinding.adAdvertiser
nativeAdView.bodyView = nativeAdBinding.adBody
nativeAdView.callToActionView = nativeAdBinding.adCallToAction
nativeAdView.headlineView = nativeAdBinding.adHeadline
nativeAdView.iconView = nativeAdBinding.adAppIcon
nativeAdView.priceView = nativeAdBinding.adPrice
nativeAdView.starRatingView = nativeAdBinding.adStars
nativeAdView.storeView = nativeAdBinding.adStore
// Set the view element with the native ad assets.
nativeAdBinding.adAdvertiser.text = nativeAd.advertiser
nativeAdBinding.adBody.text = nativeAd.body
nativeAdBinding.adCallToAction.text = nativeAd.callToAction
nativeAdBinding.adHeadline.text = nativeAd.headline
nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.icon?.drawable)
nativeAdBinding.adPrice.text = nativeAd.price
nativeAd.starRating?.toFloat().let { value ->
nativeAdBinding.adStars.rating = value
}
nativeAdBinding.adStore.text = nativeAd.store
// Hide views for assets that don't have data.
nativeAdBinding.adAdvertiser.visibility = getAssetViewVisibility(nativeAd.advertiser)
nativeAdBinding.adBody.visibility = getAssetViewVisibility(nativeAd.body)
nativeAdBinding.adCallToAction.visibility = getAssetViewVisibility(nativeAd.callToAction)
nativeAdBinding.adHeadline.visibility = getAssetViewVisibility(nativeAd.headline)
nativeAdBinding.adAppIcon.visibility = getAssetViewVisibility(nativeAd.icon)
nativeAdBinding.adPrice.visibility = getAssetViewVisibility(nativeAd.price)
nativeAdBinding.adStars.visibility = getAssetViewVisibility(nativeAd.starRating)
nativeAdBinding.adStore.visibility = getAssetViewVisibility(nativeAd.store)
// Inform GMA Next-Gen SDK that you have finished populating
// the native ad views with this native ad.
nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia)
}
/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return [View.VISIBLE] if the asset is not null, [View.INVISIBLE] otherwise.
*/
private fun getAssetViewVisibility(asset: Any?): Int {
return if (asset == null) View.INVISIBLE else View.VISIBLE
}
Java
private void displayNativeAd(ad: NativeAd, nativeAdBinding : NativeAdBinding) {
// Set the native ad view elements.
NativeAdView nativeAdView = nativeAdBinding.getRoot();
nativeAdView.setAdvertiserView(nativeAdBinding.adAdvertiser);
nativeAdView.setBodyView(nativeAdBinding.adBody);
nativeAdView.setCallToActionView(nativeAdBinding.adCallToAction);
nativeAdView.setHeadlineView(nativeAdBinding.adHeadline);
nativeAdView.setIconView(nativeAdBinding.adAppIcon);
nativeAdView.setPriceView(nativeAdBinding.adPrice);
nativeAdView.setStarRatingView(nativeAdBinding.adStars);
nativeAdView.setStoreView(nativeAdBinding.adStore);
// Set the view element with the native ad assets.
nativeAdBinding.adAdvertiser.setText(nativeAd.getAdvertiser());
nativeAdBinding.adBody.setText(nativeAd.getBody());
nativeAdBinding.adCallToAction.setText(nativeAd.getCallToAction());
nativeAdBinding.adHeadline.setText(nativeAd.getHeadline());
if (nativeAd.getIcon() != null) {
nativeAdBinding.adAppIcon.setImageDrawable(nativeAd.getIcon().getDrawable());
}
nativeAdBinding.adPrice.setText(nativeAd.getPrice());
if (nativeAd.getStarRating() != null) {
nativeAdBinding.adStars.setRating(nativeAd.getStarRating().floatValue());
}
nativeAdBinding.adStore.setText(nativeAd.getStore());
// Hide views for assets that don't have data.
nativeAdBinding.adAdvertiser.setVisibility(getAssetViewVisibility(nativeAd.getAdvertiser()));
nativeAdBinding.adBody.setVisibility(getAssetViewVisibility(nativeAd.getBody()));
nativeAdBinding.adCallToAction.setVisibility(getAssetViewVisibility(nativeAd.getCallToAction()));
nativeAdBinding.adHeadline.setVisibility(getAssetViewVisibility(nativeAd.getHeadline()));
nativeAdBinding.adAppIcon.setVisibility(getAssetViewVisibility(nativeAd.getIcon()));
nativeAdBinding.adPrice.setVisibility(getAssetViewVisibility(nativeAd.getPrice()));
nativeAdBinding.adStars.setVisibility(getAssetViewVisibility(nativeAd.getStarRating()));
nativeAdBinding.adStore.setVisibility(getAssetViewVisibility(nativeAd.getStore()));
// Inform GMA Next-Gen SDK that you have finished populating
// the native ad views with this native ad.
nativeAdView.registerNativeAd(nativeAd, nativeAdBinding.adMedia);
}
/**
* Determines the visibility of an asset view based on the presence of its asset.
*
* @param asset The native ad asset to check for nullability.
* @return {@link View#VISIBLE} if the asset is not null, {@link View#INVISIBLE} otherwise.
*/
private int getAssetViewVisibility(Object asset) {
return (asset == null) ? View.INVISIBLE : View.VISIBLE;
}
Superposition "Choisir sa pub"
Une superposition "Choisir sa pub" est ajoutée à chaque vue d'annonce par le SDK. Laissez de l'espace dans l' angle de votre choix de votre vue d'annonce native pour le logo "Choisir sa pub" inséré automatiquement. Il est également important que la superposition "Choisir sa pub" soit visible. Choisissez donc des couleurs et des images d'arrière-plan appropriées. Pour en savoir plus sur l'apparence et le fonctionnement de la superposition, consultez Descriptions des champs des annonces natives.
Attribution d'annonce
Vous devez afficher une attribution d'annonce pour indiquer que la vue est une publicité. Pour en savoir plus, consultez nos consignes concernant le règlement politique.
Gérer les clics
N'implémentez aucun gestionnaire de clics personnalisé sur les vues au-dessus ou à l'intérieur de la vue d'annonce native. Les clics sur les composants de la vue d'annonce sont gérés par le SDK tant que vous renseignez et enregistrez correctement les vues des composants.
Pour écouter les clics, implémentez le rappel de clic GMA Next-Gen SDK :
Kotlin
private fun setEventCallback(nativeAd: NativeAd) {
nativeAd.adEventCallback =
object : NativeAdEventCallback {
override fun onAdClicked() {
Log.d(Constant.TAG, "Native ad recorded a click.")
}
}
}
Java
private void setEventCallback(NativeAd nativeAd) {
nativeAd.setAdEventCallback(new NativeAdEventCallback() {
@Override
public void onAdClicked() {
Log.d(Constant.TAG, "Native ad recorded a click.");
}
});
}
ImageScaleType
La classe MediaView possède une propriété ImageScaleType lors de l'affichage d'images. Si vous souhaitez modifier la façon dont une image est mise à l'échelle dans MediaView, définissez le ImageView.ScaleType correspondant à l'aide de la méthode setImageScaleType() de MediaView :
Kotlin
nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
Java
nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
MediaContent
La classe MediaContent contient les données liées au contenu média de l'annonce native, qui est affiché à l'aide de la classe MediaView. Lorsque la propriété MediaView mediaContent est définie avec une instance MediaContent :
Si un composant vidéo est disponible, il est mis en mémoire tampon et commence à être lu dans
MediaView. Pour savoir si un composant vidéo est disponible, vérifiezhasVideoContent().Si l'annonce ne contient pas de composant vidéo, le composant
mainImageest téléchargé et placé à la place dansMediaView.
Supprimer une annonce
Une fois que vous avez diffusé une annonce native, supprimez-la. L'exemple suivant supprime une annonce native :
Kotlin
nativeAd.destroy()
Java
nativeAd.destroy();
Étapes suivantes
Consultez les rubriques suivantes :
Exemple
Téléchargez et exécutez l' exemple d'application qui illustre l'utilisation du GMA Next-Gen SDK.