顯示 NativeAd
原生廣告載入時,Google Mobile Ads SDK 會為對應的廣告格式叫用事件監聽器。接著,您的應用程式負責顯示廣告,但不一定需要立即顯示。為讓您更輕鬆地顯示系統定義的廣告格式,SDK 提供一些實用資源,如下所述。
定義 NativeAdView
類別
定義 NativeAdView
類別。這個類別是 ViewGroup
類別,也是 NativeAdView
類別的頂層容器。每個原生廣告視圖都包含原生廣告素材資源,例如 MediaView
視圖元素或 Title
視圖元素,這些元素必須是 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("/21775744923/example/native", 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("/21775744923/example/native", 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 會嘗試記錄警告。
廣告檢視畫面類別也提供方法,用於註冊用於個別素材資源的檢視畫面,以及註冊 NativeAd
物件本身。以這種方式註冊檢視畫面可讓 SDK 自動處理下列工作:
- 記錄點擊
- 在畫面上顯示第一個像素時,記錄曝光
- 為原生回補廣告素材顯示 AdChoices 重疊圖層,目前僅限部分發布商
AdChoices 重疊廣告
當 SDK 傳回候補廣告時,會將 AdChoices 疊加層加入做為廣告視圖。如果應用程式使用原生廣告回填功能,請在原生廣告檢視畫面的偏好角落留出空間,以便自動插入 AdChoices 標誌。此外,疊加在廣告中的 AdChoices 標籤必須清楚易見,因此請選用合適的背景顏色和圖片。如要進一步瞭解疊加層的外觀和功能,請參閱程式輔助原生廣告導入規範。
程式輔助原生廣告的廣告歸因
顯示程式輔助原生廣告時,您必須顯示廣告歸屬資訊,以表示該視圖是廣告。詳情請參閱政策指南。
程式碼範例
顯示原生廣告的步驟如下:
- 建立
NativeAdView
類別的例項。 針對每項要顯示的廣告素材資源:
- 使用廣告物件中的素材資源填入素材資源檢視畫面。
- 使用
NativeAdView
類別註冊素材資源檢視畫面。
使用
NativeAdView
類別註冊廣告物件。
以下是顯示 NativeAd
的範例函式:
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 the Google Mobile Ads 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 the Google Mobile Ads 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;
}
以下是個別工作:
加載版面配置
Kotlin
// Remove all old ad views when loading a new native ad. binding.nativeViewContainer.removeAllViews() // Inflate the native ad view and add it to the view hierarchy. val nativeAdBinding = NativeAdBinding.inflate(layoutInflater) binding.nativeViewContainer.addView(nativeAdBinding.root)
Java
// Remove all old ad views when loading a new native ad. binding.nativeViewContainer.removeAllViews(); // Inflate the native ad view and add it to the view hierarchy. NativeAdBinding nativeAdBinding = NativeAdBinding.inflate(getLayoutInflater()); binding.nativeViewContainer.addView(nativeAdBinding.getRoot());
這段程式碼會將 XML 版面配置加載至內含用於顯示原生廣告的檢視畫面,然後找出
NativeAdView
的參照。請注意,如果片段或活動中已有NativeAdView
,您也可以重複使用該NativeAdView
,甚至不使用版面配置檔案,也可以動態建立例項。填入並註冊資產檢視畫面
這個範例程式碼會找出用於顯示標題的檢視畫面,並使用廣告物件提供的字串素材資源設定文字,然後將其註冊至
NativeAdView
物件:Kotlin
nativeAdView.headlineView = nativeAdBinding.adHeadline nativeAdBinding.adHeadline.text = nativeAd.headline nativeAdBinding.adHeadline.visibility = getAssetViewVisibility(nativeAd.headline)
Java
nativeAdView.setHeadlineView(nativeAdBinding.adHeadline); nativeAdBinding.adHeadline.setText(nativeAd.getHeadline()); nativeAdBinding.adHeadline.setVisibility(getAssetViewVisibility(nativeAd.getHeadline()));
對於應用程式要顯示的原生廣告物件提供的每個素材資源,都應重複執行這個尋找檢視畫面、設定其值,以及向廣告檢視畫面類別註冊的程序。
處理點擊
請勿在原生廣告檢視畫面內或上方的任何檢視畫面中,實作任何自訂點擊處理常式。只要您正確填入及註冊素材資源檢視畫面 (如前一個部分所述),SDK 就會處理廣告檢視畫面素材資源的點擊次數。
如要接收點擊事件,請實作 Google Mobile Ads 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."); } }); }
註冊 MediaView
如要在原生廣告版面配置中包含主要圖片素材資源,必須使用
MediaView
素材資源,而不是ImageView
素材資源。Kotlin
// Get the media asset view. val mediaView = nativeAdBinding.adMedia
Java
// Get the media asset view. MediaView mediaView = nativeAdBinding.adMedia;
ImageScaleType
MediaView
類別在顯示圖片時具有ImageScaleType
屬性。如要變更圖片在MediaView
中的縮放方式,請使用MediaView
的setImageScaleType()
方法設定對應的ImageView.ScaleType
:Kotlin
nativeAdViewBinding.mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
Java
nativeAdViewBinding.mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
MediaContent
MediaContent
類別會保留與原生廣告媒體內容相關的資料,並使用MediaView
類別顯示。當MediaView
mediaContent
屬性設為MediaContent
例項時:如果有可用的影片素材資源,系統會進行緩衝,並開始在
MediaView
中播放。您可以檢查hasVideoContent()
,判斷影片素材資源是否可用。如果廣告不含影片素材資源,系統會下載
mainImage
素材資源,並將其放入MediaView
中。
如果使用
disableImageDownloading(true)
,mainImage
就是null
,您必須將mainImage
屬性設為手動下載的圖片。請注意,只有在沒有可用的影片素材資源時,系統才會使用這張圖片。註冊原生廣告物件
這個最後步驟會將原生廣告物件註冊至負責顯示該廣告的檢視畫面,以及媒體內容素材資源的檢視畫面。
Kotlin
// Inform the Google Mobile Ads SDK that you have finished populating // the native ad views with this native ad and media content asset. nativeAdView.registerNativeAd(nativeAd, mediaView)
Java
// Inform the Google Mobile Ads SDK that you have finished populating // the native ad views with this native ad and media content asset. nativeAdView.registerNativeAd(nativeAd, mediaView);
銷毀廣告
原生廣告顯示完畢後,您應將其銷毀,以便系統正確進行垃圾收集。
Kotlin
nativeAd.destroy()
Java
nativeAd.destroy();
測試原生廣告程式碼
直接銷售廣告
如果您想測試直接銷售的原生廣告,可以使用這個 Ad Manager 廣告單元 ID:
/21775744923/example/native
這項廣告活動已設定為放送範例應用程式安裝廣告和內容廣告,以及使用下列素材資源的自訂原生廣告格式:
- 廣告標題 (文字)
- MainImage (圖片)
- 說明文字 (文字)
自訂原生廣告格式的範本 ID 為 10063170
。
原生候補廣告
Ad Exchange 後端填充功能僅適用於特定發布商群組。如要測試原生候補廣告的行為,請使用下列 Ad Manager 廣告單元:
/21775744923/example/native-backfill
這份範例檔案會刊登含有 AdChoices 重疊層的應用程式安裝廣告和內容廣告。
請記得在正式上線前更新程式碼,以便參照實際的廣告單元和範本 ID。
後續步驟
請參閱下列主題:
範例
下載並執行範例應用程式,瞭解如何使用 Next Gen Google Mobile Ads SDK。