原生進階

顯示 NativeAd

原生廣告載入時,Google Mobile Ads SDK 會叫用對應廣告格式的事件監聽器。接著,您的應用程式會負責顯示廣告,但不一定要立即執行這項操作。為方便您顯示系統定義的廣告格式,SDK 提供幾項實用資源,如下所述。

NativeAdView 類別

如果是 NativeAd 格式,則有對應的 NativeAdView 類別。此類別是 ViewGroup,發布者應做為 NativeAd 的根層級。一個 NativeAdView 對應一個原生廣告。用來顯示該廣告素材資源的每個檢視畫面 (例如顯示螢幕截圖素材資源的 ImageView) 都必須是 NativeAdView 物件的子項。

使用 LinearLayout 顯示素材資源檢視畫面的原生廣告檢視區塊階層,看起來可能就像這樣:

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


         // Other assets such as image or media view, call to action, etc follow.
         ...
    </LinearLayout>
</com.google.android.gms.ads.nativead.NativeAdView>

以下範例說明如何建立 NativeAdView 並填入 NativeAd

Java

AdLoader.Builder builder = new AdLoader.Builder(this, "AD_UNIT_ID")
    .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 text, images and the native ad, etc into the ad
            // view.
            populateNativeAdView(nativeAd, adView);
            frameLayout.removeAllViews();
            frameLayout.addView(adView);
        }
});

Kotlin

val builder = AdLoader.Builder(this, "AD_UNIT_ID")
    .forNativeAd { nativeAd ->
        // 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 text, images and the native ad, etc into the ad
        // view.
        populateNativeAdView(nativeAd, adView)
        // Assumes you have a placeholder FrameLayout in your View layout
        // (with id ad_frame) where the ad is to be placed.
        ad_frame.removeAllViews()
        ad_frame.addView(adView)
    }

請注意,特定原生廣告的所有素材資源都必須在 NativeAdView 版面配置內顯示。原生素材資源在原生廣告檢視版面配置外顯示時,Google Mobile Ads SDK 會嘗試記錄一次警告。

廣告檢視畫面類別也提供用於註冊每項個別素材資源的檢視畫面,以及註冊 NativeAd 物件本身的方法。以這種方式註冊檢視畫面,可讓 SDK 自動處理以下工作:

  • 記錄點擊
  • 畫面上出現第一個像素時記錄曝光
  • 針對原生候補廣告素材, 顯示 AdChoices 重疊廣告 (目前僅限特定發布商群組)

AdChoices 重疊廣告

SDK 傳回候補廣告時,會把 AdChoices 重疊廣告新增為廣告檢視畫面。如果您的應用程式使用原生廣告候補廣告,請在原生廣告檢視畫面中的首選角落保留空間,讓系統自動插入 AdChoices 標誌。此外,請務必讓 AdChoices 重疊元素顯而易見,因此請選擇合適的背景顏色和圖片。如要進一步瞭解重疊廣告的外觀和功能,請參閱程式輔助原生廣告導入指南

程式輔助原生廣告的廣告歸因

顯示程式輔助原生廣告時,您必須顯示廣告標示,表明資料檢視是廣告。詳情請參閱我們的政策規範

程式碼範例

顯示原生廣告的步驟如下:

  1. 建立 NativeAdView 類別的執行個體。
  2. 針對每個要顯示的廣告素材資源:
    1. 為素材資源檢視畫面填入廣告物件中的素材資源。
    2. 使用 ViewGroup 類別註冊資產檢視畫面。
  3. 如果原生廣告版面配置包含大型媒體素材資源,請註冊 MediaView
  4. 使用 ViewGroup 類別註冊廣告物件。

以下是顯示 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 above 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 above 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)
}

以下是個別工作:

  1. 加載版面配置

    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
    

    這個程式碼會加載 XML 版面配置,其中包含用於顯示原生廣告的檢視畫面,然後找出 NativeAdView 的參照。請注意,如果片段或活動中有現有的 NativeAdView,甚至在不使用版面配置檔案的情況下動態建立執行個體,您也可以重複使用現有的 NativeAdView

  2. 填入並登錄資產檢視畫面

    此程式碼範例會找出用來顯示廣告標題的檢視畫面、使用廣告物件提供的字串素材資源設定其文字,然後使用 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
    

    我們會針對應用程式將顯示的原生廣告物件所提供的每個素材資源,重複找出檢視畫面、設定其值,並向廣告檢視類別註冊的程序。

  3. 處理點擊

    請勿在原生廣告檢視畫面的任一檢視畫面上,導入任何自訂點擊處理常式。如要自行觀察點擊事件,請使用廣告事件監聽器

    只要正確填入並登錄素材資源檢視畫面,如上一節所述,SDK 就會處理廣告瀏覽素材資源的點擊次數。

    以下範例使用廣告事件監聽器觀察點擊事件:

    Java

    AdLoader adLoader = new AdLoader.Builder(context, "/6499/example/native")
        ...
        .withAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(LoadAdError adError) {
                // Handle the failure by logging, altering the UI, and so on.
            }
            @Override
            public void onAdClicked() {
                // Log the click event or other custom behavior.
            }
        })
        .build();
    

    Kotlin

    val adLoader = AdLoader.Builder(this, "/6499/example/native")
        ...
        .withAdListener(object : AdListener() {
            override fun onAdFailedToLoad(adError: LoadAdError) {
                // Handle the failure by logging, altering the UI, and so on.
            }
        })
        .build()
    
  4. 註冊 MediaView

    如要在原生廣告的版面配置中加入主要圖片素材資源,必須使用 MediaView 素材資源,而非 ImageView

    MediaView 是特殊的 View,專為顯示影片或圖片的主要媒體素材資源而設計。

    MediaView 可以在 XML 版面配置中定義,也可以動態建構。這類檔案應放在 NativeAdView 的檢視區塊階層中,就像任何其他資產檢視畫面一樣。使用 MediaView 的應用程式必須向 NativeAdView 註冊:

    Java

    MediaView mediaView = adView.findViewById(R.id.ad_media);
    adView.setMediaView(mediaView);
    

    Kotlin

    adView.mediaView = adView.findViewById<MediaView>(R.id.ad_media)
    

    與所有資產檢視畫面一樣,媒體檢視畫面都必須填入內容。這是使用 getMediaContent() 方法擷取可傳遞至 MediaView媒體內容。以下程式碼片段說明如何設定媒體檢視畫面的媒體內容:

    Java

    mediaView.setMediaContent(nativeAd.getMediaContent());
    

    Kotlin

    mediaView.mediaContent = nativeAd.mediaContent
    

    ImageScaleType

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

    Java

    mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
    

    Kotlin

    mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
    

    MediaContent

    MediaContent 類別會保留與原生廣告媒體內容相關的資料,這些內容透過 MediaView 類別顯示。使用 MediaContent 執行個體設定 MediaView mediaContent 屬性時:

    • 如果有可用的影片資產,系統會緩衝並在 MediaView 中開始播放。您可以檢查 hasVideoContent(),判斷是否有影片素材資源。

    • 如果廣告不包含影片素材資源,系統會改為下載 mainImage 素材資源,並放在 MediaView 中。

    根據預設,mainImage 是第一個下載的圖片素材資源。如果使用 setReturnUrlsForImageAssets(true),則 mainImagenull,且您必須將 mainImage 屬性設為手動下載的圖片。請注意,只有在沒有可用的影片素材資源時,系統才會顯示這張圖片。

  5. 註冊原生廣告物件

    最後的步驟會向負責顯示原生廣告物件的檢視畫面註冊:

    Java

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

刪除廣告

顯示原生廣告後,建議您刪除,讓系統正確收集廣告。

Java

nativeAd.destroy();
        .inflate(R.layout.ad_layout_file, parent);

Kotlin

nativeAd.destroy()

測試原生廣告程式碼

直接銷售廣告

如果您想測試直接銷售的原生廣告外觀,可以使用下列 Ad Manager 廣告單元 ID:

/6499/example/native

設為放送範例應用程式安裝廣告和內容廣告,以及使用下列素材資源的自訂原生廣告格式:

  • 標題 (文字)
  • 主要圖片 (圖片)
  • 說明文字 (文字)

自訂原生廣告格式的範本 ID 為 10063170

原生候補廣告

Ad Exchange 候補廣告目前只適用於特定發布商群組。如要測試原生候補廣告的行為,請使用這個 Ad Manager 廣告單元:

/6499/example/native-backfill

這個範例提供應用程式安裝和內含 AdChoices 重疊廣告的內容廣告。

別忘了更新程式碼,參照實際的廣告單元和範本 ID 再上線。

GitHub 上的範例

完整導入原生廣告範例:

Java Kotlin

後續步驟

探索下列主題: