Muestra un objeto NativeAd
Cuando se carga un anuncio nativo, el SDK de anuncios de Google para dispositivos móviles invoca el objeto de escucha para el formato de anuncio correspondiente. Luego, tu app debe mostrar el anuncio (aunque no necesariamente de inmediato). Para facilitar la visualización de los formatos de anuncio definidos por el sistema, el SDK ofrece algunos recursos útiles, como se describe a continuación.
Cómo definir la clase NativeAdView
Define una clase NativeAdView
. Esta clase es de tipo ViewGroup
y es el contenedor de nivel superior de una clase NativeAdView
. Cada vista de anuncio nativo contiene recursos de anuncio de este tipo, como los elementos de vista MediaView
o Title
, que deben ser un elemento secundario del objeto NativeAdView
.
Diseño XML
Agrega un NativeAdView
XML a tu proyecto:
<com.google.android.gms.ads.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.gms.ads.nativead.NativeAdView>
Jetpack Compose
Incluye el módulo JetpackComposeDemo/compose-util, que incluye asistentes para componer el NativeAdView
y sus recursos.
Con el módulo compose-util
, compón 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.
}
}
Controla el anuncio nativo cargado
Cuando se cargue un anuncio nativo, controla el evento de devolución de llamada, aumenta la vista del anuncio nativo y agrégala a la jerarquía de vistas:
Java
AdLoader.Builder builder = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
.forNativeAd(new NativeAd.OnNativeAdLoadedListener() {
@Override
public void onNativeAdLoaded(NativeAd nativeAd) {
// Assumes you have a placeholder FrameLayout in your View layout
// (with ID fl_adplaceholder) where the ad is to be placed.
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
// Assumes that your ad layout is in a file call native_ad_layout.xml
// in the res/layout folder
NativeAdView adView = (NativeAdView) getLayoutInflater()
.inflate(R.layout.native_ad_layout, null);
// This method sets the assets into the ad view.
populateNativeAdView(nativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
Kotlin
val builder = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
.forNativeAd { nativeAd ->
// Assumes you have a placeholder FrameLayout in your View layout
// (with ID fl_adplaceholder) where the ad is to be placed.
val frameLayout: FrameLayout = findViewById(R.id.fl_adplaceholder)
// Assumes that your ad layout is in a file call native_ad_layout.xml
// in the res/layout folder
val adView = layoutInflater
.inflate(R.layout.native_ad_layout, null) as NativeAdView
// This method sets the assets into the ad view.
populateNativeAdView(nativeAd, adView)
frameLayout.removeAllViews()
frameLayout.addView(adView)
}
Jetpack Compose
@Composable
/** Load and display a native ad. */
fun NativeScreen() {
var nativeAd by remember { mutableStateOf<NativeAd?>(null) }
val context = LocalContext.current
var isDisposed by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
// Load the native ad when we launch this screen
loadNativeAd(
context = context,
onAdLoaded = { ad ->
// Handle the native ad being loaded.
if (!isDisposed) {
nativeAd = ad
} else {
// Destroy the native ad if loaded after the screen is disposed.
ad.destroy()
}
},
)
// Destroy the native ad to prevent memory leaks when we dispose of this screen.
onDispose {
isDisposed = true
nativeAd?.destroy()
nativeAd = null
}
}
// Display the native ad view with a user defined template.
nativeAd?.let { adValue -> DisplayNativeAdView(adValue) }
}
fun loadNativeAd(context: Context, onAdLoaded: (NativeAd) -> Unit) {
val adLoader =
AdLoader.Builder(context, NATIVE_AD_UNIT_ID)
.forNativeAd { nativeAd -> onAdLoaded(nativeAd) }
.withAdListener(
object : AdListener() {
override fun onAdFailedToLoad(error: LoadAdError) {
Log.e(TAG, "Native ad failed to load: ${error.message}")
}
override fun onAdLoaded() {
Log.d(TAG, "Native ad was loaded.")
}
override fun onAdImpression() {
Log.d(TAG, "Native ad recorded an impression.")
}
override fun onAdClicked() {
Log.d(TAG, "Native ad was clicked.")
}
}
)
.build()
adLoader.loadAd(AdRequest.Builder().build())
}
Ten en cuenta que todos los recursos de cada anuncio nativo se deben renderizar dentro del diseño de NativeAdView
.
El SDK de anuncios de Google para dispositivos móviles intenta registrar una advertencia cuando los recursos nativos se renderizan fuera del diseño de la vista de un anuncio nativo.
Las clases de vistas de anuncios también proporcionan métodos que se usan para registrar la vista utilizada para cada recurso individual y uno para registrar el objeto NativeAd
en sí.
Registrar las vistas de esta manera permite que el SDK controle automáticamente tareas como las siguientes:
- Registrar clics
- Registrar impresiones cuando el primer píxel es visible en la pantalla
- Mostrar la superposición de AdChoices
Superposición de AdChoices
El SDK agrega una superposición de AdChoices a cada vista de anuncio. Deja espacio en la esquina que prefieras de la vista de tu anuncio nativo para el logotipo de AdChoices que se inserta automáticamente. Además, es importante que la superposición de AdChoices se vea con facilidad, por lo que debes elegir imágenes y colores de fondo adecuados. Para obtener más información sobre la apariencia y la función de la superposición, consulta las descripciones de los campos de los anuncios nativos.
Atribución de anuncio
Debes mostrar una atribución de anuncio para indicar que la vista es un anuncio. Obtén más información en nuestros lineamientos de políticas.
Ejemplo de código
Estos son los pasos que debes seguir para mostrar un anuncio nativo:
- Crea una instancia de la clase
NativeAdView
. Para publicar cada recurso del anuncio, haz lo siguiente:
- Completa la vista del recurso con el recurso del objeto del anuncio.
- Registra la vista del recurso con la clase
NativeAdView
.
Registra
MediaView
si el diseño de tu anuncio nativo incluye un elemento multimedia grande.Registra el objeto de anuncio con la clase
NativeAdView
.
A continuación, se muestra un ejemplo de una función que muestra un NativeAd
:
Java
private void displayNativeAd(ViewGroup parent, NativeAd ad) {
// Inflate a layout and add it to the parent ViewGroup.
LayoutInflater inflater = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
NativeAdView adView = (NativeAdView) inflater
.inflate(R.layout.ad_layout_file, parent);
// Locate the view that will hold the headline, set its text, and call the
// NativeAdView's setHeadlineView method to register it.
TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline);
headlineView.setText(ad.getHeadline());
adView.setHeadlineView(headlineView);
// Repeat the process for the other assets in the NativeAd
// using additional view objects (Buttons, ImageViews, etc).
// If the app is using a MediaView, it should be
// instantiated and passed to setMediaView. This view is a little different
// in that the asset is populated automatically, so there's one less step.
MediaView mediaView = (MediaView) adView.findViewById(R.id.ad_media);
adView.setMediaView(mediaView);
// Call the NativeAdView's setNativeAd method to register the
// NativeAdObject.
adView.setNativeAd(ad);
// Ensure that the parent view doesn't already contain an ad view.
parent.removeAllViews();
// Place the AdView into the parent.
parent.addView(adView);
}
Kotlin
fun displayNativeAd(parent: ViewGroup, ad: NativeAd) {
// Inflate a layout and add it to the parent ViewGroup.
val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
as LayoutInflater
val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView
// Locate the view that will hold the headline, set its text, and use the
// NativeAdView's headlineView property to register it.
val headlineView = adView.findViewById<TextView>(R.id.ad_headline)
headlineView.text = ad.headline
adView.headlineView = headlineView
// Repeat the process for the other assets in the NativeAd using
// additional view objects (Buttons, ImageViews, etc).
val mediaView = adView.findViewById<MediaView>(R.id.ad_media)
adView.mediaView = mediaView
// Call the NativeAdView's setNativeAd method to register the
// NativeAdObject.
adView.setNativeAd(ad)
// Ensure that the parent view doesn't already contain an ad view.
parent.removeAllViews()
// Place the AdView into the parent.
parent.addView(adView)
}
Jetpack Compose
@Composable
/** Display a native ad with a user defined template. */
fun DisplayNativeAdView(nativeAd: NativeAd) {
val context = LocalContext.current
Box(modifier = Modifier.padding(8.dp).wrapContentHeight(Alignment.Top)) {
// Call the NativeAdView composable to display the native ad.
NativeAdView {
// Inside the NativeAdView composable, display the native ad assets.
Column(Modifier.align(Alignment.TopStart).wrapContentHeight(Alignment.Top)) {
// Display the ad attribution.
NativeAdAttribution(text = context.getString(R.string.attribution))
Row {
// If available, display the icon asset.
nativeAd.icon?.let { icon ->
NativeAdIconView(Modifier.padding(5.dp)) {
icon.drawable?.toBitmap()?.let { bitmap ->
Image(bitmap = bitmap.asImageBitmap(), "Icon")
}
}
}
Column {
// If available, display the headline asset.
nativeAd.headline?.let {
NativeAdHeadlineView {
Text(text = it, style = MaterialTheme.typography.headlineLarge)
}
}
// If available, display the star rating asset.
nativeAd.starRating?.let {
NativeAdStarRatingView {
Text(text = "Rated $it", style = MaterialTheme.typography.labelMedium)
}
}
}
}
// If available, display the body asset.
nativeAd.body?.let { NativeAdBodyView { Text(text = it) } }
// Display the media asset.
NativeAdMediaView(Modifier.fillMaxWidth().height(500.dp).fillMaxHeight())
Row(Modifier.align(Alignment.End).padding(5.dp)) {
// If available, display the price asset.
nativeAd.price?.let {
NativeAdPriceView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
Text(text = it)
}
}
// If available, display the store asset.
nativeAd.store?.let {
NativeAdStoreView(Modifier.padding(5.dp).align(Alignment.CenterVertically)) {
Text(text = it)
}
}
// If available, display the call to action asset.
// Note: The Jetpack Compose button implements a click handler which overrides the native
// ad click handler, causing issues. Use the NativeAdButton which does not implement a
// click handler. To handle native ad clicks, use the NativeAd AdListener onAdClicked
// callback.
nativeAd.callToAction?.let { callToAction ->
NativeAdCallToActionView(Modifier.padding(5.dp)) { NativeAdButton(text = callToAction) }
}
}
}
}
}
}
Estas son las tareas individuales:
Aumenta el diseño
Java
LayoutInflater inflater = (LayoutInflater) parent.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); NativeAdView adView = (NativeAdView) inflater .inflate(R.layout.ad_layout_file, parent);
Kotlin
val inflater = parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val adView = inflater.inflate(R.layout.ad_layout_file, parent) as NativeAdView
Este código aumenta un diseño XML que contiene vistas para mostrar un anuncio nativo y, luego, ubica una referencia al objeto
NativeAdView
. Ten en cuenta que también puedes reutilizar unNativeAdView
existente si hay uno en tu fragmento o actividad, o incluso crear una instancia de forma dinámica sin usar un archivo de diseño.Completa y registra las vistas de recursos
Este código de muestra ubica la vista utilizada para mostrar el título, establece su texto con el recurso de cadena proporcionado por el objeto del anuncio y lo registra con el objeto
NativeAdView
:Java
TextView headlineView = adView.findViewById<TextView>(R.id.ad_headline); headlineView.setText(ad.getHeadline()); adView.setHeadlineView(headlineView);
Kotlin
val headlineView = adView.findViewById<TextView>(R.id.ad_headline) headlineView.text = ad.headline adView.headlineView = headlineView
El proceso de ubicar la vista, establecer su valor y registrarla con la clase de vista del anuncio se debe repetir para cada uno de los recursos proporcionados por el objeto del anuncio nativo que mostrará la app.
Controla los clics
No implementes ningún controlador de clics personalizado en ninguna vista sobre la vista del anuncio nativo o dentro de ella. El SDK controla los clics en los recursos de vistas de anuncios, siempre y cuando completes y registres correctamente las vistas de recursos, tal como se explicó en la sección anterior.
Para escuchar los clics, implementa la devolución de llamada de clics del SDK de anuncios de Google para dispositivos móviles:
Java
AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110") // ... .withAdListener(new AdListener() { @Override public void onAdFailedToLoad(LoadAdError adError) { // Handle the failure by logging. } @Override public void onAdClicked() { // Log the click event or other custom behavior. } }) .build();
Kotlin
val adLoader = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110") // ... .withAdListener(object : AdListener() { override fun onAdFailedToLoad(adError: LoadAdError) { // Handle the failure. } override fun onAdClicked() { // Log the click event or other custom behavior. } }) .build()
Registra el MediaView
Si deseas incluir un recurso de imagen principal en el diseño del anuncio nativo, debes utilizar el recurso
MediaView
en lugar deImageView
.El
MediaView
es unView
especial diseñado para mostrar el recurso multimedia principal, ya sea un video o una imagen.El
MediaView
se puede definir en un diseño XML o se puede construir de forma dinámica. Se debe colocar dentro de la jerarquía de vistas de unNativeAdView
, al igual que cualquier otra vista de recursos. Las apps que usan unMediaView
deben registrarlo con elNativeAdView
:Java
// Populate and register the media asset view. nativeAdView.setMediaView(nativeAdBinding.adMedia);
Kotlin
// Populate and register the media asset view. nativeAdView.mediaView = nativeAdBinding.adMedia
ImageScaleType
La clase
MediaView
tiene una propiedadImageScaleType
cuando se muestran imágenes. Si quieres cambiar la forma en que se ajusta el tamaño de una imagen en elMediaView
, establece elImageView.ScaleType
correspondiente con el métodosetImageScaleType()
delMediaView
:Java
mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
Kotlin
mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
MediaContent
La clase
MediaContent
contiene los datos relacionados con el contenido multimedia del anuncio nativo, que se muestra con la claseMediaView
. Cuando la propiedadMediaView
mediaContent
se establece con una instancia deMediaContent
, ocurre lo siguiente:Si hay un recurso de video disponible, se almacena en el búfer y comienza a reproducirse dentro de
MediaView
. Para saber si un recurso de video está disponible, consultahasVideoContent()
.Si el anuncio no contiene un recurso de video, el recurso
mainImage
se descarga y se coloca en elMediaView
.
De forma predeterminada,
mainImage
es el primer recurso de imagen que se descarga. Si se usasetReturnUrlsForImageAssets(true)
,mainImage
esnull
, y debes establecer la propiedadmainImage
en la imagen que descargaste manualmente. Ten en cuenta que esta imagen solo se usará cuando no haya un recurso de video disponible.Registra el objeto de anuncio nativo
En este último paso, se registra el objeto del anuncio nativo con la vista a cargo de mostrarlo.
Java
adView.setNativeAd(ad);
Kotlin
adView.setNativeAd(ad)
Cómo destruir un anuncio
Después de mostrar un anuncio nativo, destrúyelo. El siguiente ejemplo muestra cómo se destruye un anuncio nativo:
Java
nativeAd.destroy();
Kotlin
nativeAd.destroy()
Ejemplos en GitHub
Ejemplo de implementación completa de anuncios nativos:
Próximos pasos
Explora los siguientes temas: