原生廣告

原生廣告載入時,Google Mobile Ads SDK (Beta 版) 會叫用相應廣告格式的事件監聽器,然後由應用程式顯示廣告 (不必立即顯示)。SDK 會提供一些實用資源,方便顯示系統定義的廣告格式,詳見下文。

定義 NativeAdView 類別

定義 NativeAdView 類別。這是 ViewGroup 類別,也是 NativeAdView 類別的頂層容器。每個原生廣告檢視區塊都包含原生廣告素材資源 (例如 MediaViewTitle 檢視區塊元素),這類素材資源須為 NativeAdView 物件的子項。

XML 版面配置

在專案中新增 XML NativeAdView

<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

加入 JetpackComposeDemo/compose-util 模組,其中包含用於撰寫 NativeAdView 及素材資源的輔助程式。

使用 compose-util 模組撰寫 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.
        }
    }

處理已載入的原生廣告

載入原生廣告時,請處理回呼事件、加載原生廣告檢視區塊,並加到檢視區塊階層:

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);

請注意,原生廣告的素材資源都應該在 NativeAdView 版面配置內顯示。如果原生素材資源顯示在原生廣告檢視區塊版面配置之外,Google Mobile Ads SDK (Beta 版) 會嘗試記錄警告。

廣告檢視區塊類別提供多種方法,可註冊個別素材資源使用的檢視區塊,還有一個方法可註冊 NativeAd 物件。以這種方式註冊檢視區塊,SDK 就能自動處理下列工作:

  • 記錄點擊次數
  • 記錄曝光 (畫面顯示第一個像素時)
  • 顯示 AdChoices 疊加層

顯示原生廣告

以下範例示範如何顯示原生廣告:

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 Google Mobile Ads SDK (beta) 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 Google Mobile Ads SDK (beta) 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;
}

AdChoices 疊加層

SDK 會在每個廣告檢視區塊加入 AdChoices 疊加層。在原生廣告檢視區塊保留偏好的角落,供系統自動插入 AdChoices 標誌。疊加在廣告中的 AdChoices 標籤須清楚易見,請選用合適的背景顏色和圖片。請參閱原生廣告欄位說明,進一步瞭解疊加層的外觀和功能。

廣告歸因

務必顯示廣告標示,表明觀看內容為廣告。 詳情請參閱政策規範

處理點擊

請勿在原生廣告檢視區塊上方或內部,導入任何自訂點擊處理常式。只要正確填入並註冊素材資源檢視區塊,SDK 就會處理廣告檢視區塊素材資源的點擊行為。

如要監聽點擊事件,請導入 Google Mobile Ads SDK (Beta 版) 點擊回呼:

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

顯示圖片時,MediaView 類別具備 ImageScaleType 屬性。如要變更圖片在 MediaView 中的縮放方式,請使用 MediaViewsetImageScaleType() 方法,設定對應的 ImageView.ScaleType

Kotlin

nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP

Java

nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);

MediaContent

MediaContent 類別會保留與原生廣告媒體內容相關的資料,並使用 MediaView 類別顯示。使用 MediaContent 執行個體設定 MediaView mediaContent 屬性時,請注意以下事項:

  • 如有可用的影片素材資源,該影片會緩衝處理並開始於 MediaView 播放。您可以檢查 hasVideoContent(),判斷是否有影片素材資源。

  • 如果廣告不含影片素材資源,系統會改為下載 mainImage 素材資源,並加進 MediaView

刪除廣告

請將顯示過的原生廣告刪除。以下範例會刪除原生廣告:

Kotlin

nativeAd.destroy()

Java

nativeAd.destroy();

後續步驟

請參閱下列主題:

範例

請下載並執行範例應用程式,瞭解如何使用 Google Mobile Ads SDK (Beta 版)。