Nativo avanzado

Selecciona la plataforma: Android iOS

Cómo mostrar 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 será responsable de mostrar el anuncio, aunque no necesariamente deba hacerlo de inmediato. Para facilitar la visualización de los formatos de anuncios 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 una clase ViewGroup y es el contenedor de nivel superior para una clase NativeAdView. Cada vista de anuncio nativo contiene recursos de anuncios nativos, como el elemento de vista MediaView o el elemento de vista Title, que debe 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, crea 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.
        }
    }

Cómo controlar el anuncio nativo cargado

Cuando se carga un anuncio nativo, controla el evento de devolución de llamada, infla 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 un anuncio nativo determinado 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 anuncios nativos.

Las clases de vistas de anuncios también proporcionan métodos que se usan para registrar la vista que se usa 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:

  • Clics de grabación
  • Registro de impresiones cuando el primer píxel es visible en la pantalla
  • Cómo 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 preferida 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 los colores de fondo y las imágenes de forma adecuada. Para obtener más información sobre la apariencia y la función de la superposición, consulta 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 para mostrar un anuncio nativo:

  1. Crea una instancia de la clase NativeAdView.
  2. Para que se muestre cada recurso del anuncio, debe cumplirse lo siguiente:

    1. Propaga la vista de recursos con el recurso del objeto del anuncio.
    2. Registra la vista del recurso con la clase NativeAdView.
  3. Registra MediaView si el diseño de tu anuncio nativo incluye un elemento multimedia grande.

  4. 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:

  1. Aumentar 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 NativeAdView. Ten en cuenta que también puedes reutilizar un NativeAdView 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.

  2. Propaga y registra las vistas de recursos

    En este código de muestra, se ubica la vista que se usa para mostrar el título, se establece su texto con el recurso de cadena proporcionado por el objeto del anuncio y se 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
    

    Este proceso de ubicar la vista, establecer su valor y registrarla con la clase de vista del anuncio debe repetirse para cada uno de los recursos proporcionados por el objeto del anuncio nativo que mostrará la app.

  3. 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, como se explicó en la sección anterior.

    Para detectar clics, implementa la devolución de llamada de clic 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()
    
  4. Registra el MediaView

    Si deseas incluir un elemento de imagen principal en el diseño del anuncio nativo, debes utilizar el elemento MediaView en lugar de ImageView.

    El MediaView es un View especial diseñado para mostrar el recurso de medios principal, ya sea un video o una imagen.

    MediaView se puede definir en un diseño XML o construir de forma dinámica. Se debe colocar dentro de la jerarquía de vistas de un NativeAdView, al igual que cualquier otra vista de recursos. Las apps que usan un MediaView deben registrarlo con NativeAdView:

    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 propiedad ImageScaleType cuando se muestran imágenes. Si quieres cambiar la forma en que se ajusta el tamaño de una imagen en el MediaView, configura el ImageView.ScaleType correspondiente con el método setImageScaleType() del MediaView:

    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 clase MediaView. Cuando la propiedad MediaView mediaContent se establece con una instancia de MediaContent, sucede lo siguiente:

    • Si hay un activo de video disponible, se almacena en el búfer y comienza a reproducirse dentro de MediaView. Puedes saber si un recurso de video está disponible verificando hasVideoContent().

    • Si el anuncio no contiene un recurso de video, se descarga el recurso mainImage y se coloca dentro del MediaView.

    De forma predeterminada, mainImage es el primer recurso de imagen que se descarga. Si se usa setReturnUrlsForImageAssets(true), mainImage es null y debes establecer la propiedad mainImage en la imagen que descargaste de forma manual. Ten en cuenta que esta imagen solo se usará cuando no haya un activo de video disponible.

  5. Registra el objeto de anuncio nativo

    En este último paso, se registra el objeto del anuncio nativo con la vista responsable de mostrarlo.

    Java

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

Destruye un anuncio

Después de mostrar un anuncio nativo, destrúyelo. En el siguiente ejemplo, se destruye un anuncio nativo:

Java

nativeAd.destroy();

Kotlin

nativeAd.destroy()

Ejemplos en GitHub

Ejemplo de implementación completa de anuncios nativos:

Java Kotlin JetpackCompose

Próximos pasos

Explora los siguientes temas: