Hiển thị NativeAd
Khi một quảng cáo gốc tải, SDK Quảng cáo của Google trên thiết bị di động sẽ gọi trình xử lý để có định dạng quảng cáo tương ứng. Sau đó, ứng dụng của bạn sẽ chịu trách nhiệm hiển thị quảng cáo, mặc dù ứng dụng không nhất thiết phải làm việc đó ngay lập tức. Để giúp hiển thị các định dạng quảng cáo do hệ thống xác định một cách dễ dàng hơn, SDK sẽ cung cấp một số tài nguyên hữu ích như mô tả bên dưới.
Xác định lớp NativeAdView
Xác định một lớp NativeAdView
. Lớp này là một lớp ViewGroup
và là vùng chứa cấp cao nhất cho lớp NativeAdView
. Mỗi khung hiển thị quảng cáo gốc đều chứa các thành phần quảng cáo gốc, chẳng hạn như phần tử khung hiển thị MediaView
hoặc phần tử khung hiển thị Title
. Các thành phần này phải là đối tượng con của đối tượng NativeAdView
.
Bố cục XML
Thêm một NativeAdView
XML vào dự án của bạn:
<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
Bao gồm mô-đun JetpackComposeDemo/compose-util, trong đó có các trình trợ giúp để tạo NativeAdView
và tài sản của mô-đun này.
Sử dụng mô-đun compose-util
, hãy tạo một 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.
}
}
Xử lý quảng cáo gốc đã tải
Khi một quảng cáo gốc tải, hãy xử lý sự kiện lệnh gọi lại, tăng chế độ xem quảng cáo gốc và thêm chế độ xem đó vào hệ phân cấp chế độ xem:
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())
}
Xin lưu ý rằng tất cả thành phần của một quảng cáo gốc nhất định phải hiển thị bên trong bố cục NativeAdView
. SDK Quảng cáo của Google trên thiết bị di động sẽ tìm cách ghi lại cảnh báo khi các thành phần gốc hiển thị bên ngoài bố cục chế độ xem quảng cáo gốc.
Các lớp chế độ xem quảng cáo cũng cung cấp phương thức dùng để đăng ký chế độ xem được sử dụng cho từng tài sản riêng lẻ và một phương thức để đăng ký chính đối tượng NativeAd
.
Việc đăng ký các chế độ xem theo cách này cho phép SDK tự động xử lý các công việc, chẳng hạn như:
- Ghi lại các lượt nhấp
- Ghi lại các lượt hiển thị khi pixel đầu tiên hiển thị trên màn hình
- Hiển thị lớp phủ Lựa chọn quảng cáo
Lớp phủ Lựa chọn quảng cáo
SDK sẽ thêm lớp phủ Lựa chọn quảng cáo vào từng chế độ xem quảng cáo. Hãy để trống góc ưa thích của chế độ xem quảng cáo gốc để hệ thống tự động chèn biểu trưng Lựa chọn quảng cáo. Ngoài ra, lớp phủ Lựa chọn quảng cáo phải trông thật dễ nhìn, vì vậy, bạn hãy chọn màu nền và hình ảnh phù hợp. Để biết thêm thông tin về hình thức và chức năng của lớp phủ, hãy xem Nội dung mô tả trường quảng cáo gốc.
Thuộc tính quảng cáo
Bạn phải hiển thị một thuộc tính quảng cáo để biểu thị rằng chế độ xem đó là quảng cáo. Hãy xem nguyên tắc chính sách của chúng tôi để biết thêm thông tin.
Ví dụ về mã
Dưới đây là các bước cần thực hiện để hiển thị quảng cáo gốc:
- Tạo một bản sao của lớp
NativeAdView
. Đối với mỗi thành phần quảng cáo sẽ hiển thị:
- Điền vào chế độ xem thành phần bằng thành phần trong đối tượng quảng cáo.
- Đăng ký chế độ xem tài sản bằng lớp
NativeAdView
.
Đăng ký
MediaView
nếu bố cục quảng cáo gốc bao gồm một thành phần nội dung nghe nhìn có dung lượng lớn.Đăng ký đối tượng quảng cáo bằng lớp
NativeAdView
.
Dưới đây là một hàm mẫu sẽ hiển thị 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) }
}
}
}
}
}
}
Sau đây là các nhiệm vụ riêng lẻ:
Tăng cường bố cục
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
Mã này đang tăng cường sử dụng một bố cục XML có chứa các khung hiển thị để hiển thị một quảng cáo gốc, sau đó xác định vị trí một mục tham chiếu đến
NativeAdView
. Xin lưu ý rằng bạn cũng có thể sử dụng lạiNativeAdView
hiện có nếu chế độ xem đó có trong mảnh hoặc hoạt động của bạn, hay thậm chí là tự động tạo một bản sao mà không cần sử dụng tệp bố cục.Điền và đăng ký chế độ xem tài sản
Mã mẫu này sẽ định vị chế độ xem dùng để hiển thị dòng tiêu đề, đặt văn bản của dòng tiêu đề đó bằng cách sử dụng phần tử chuỗi do đối tượng quảng cáo cung cấp và đăng ký phần tử đó với đối tượng
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
Quy trình này gồm định vị chế độ xem, đặt giá trị chế độ xem cũng như đăng ký chế độ xem bằng lớp chế độ xem quảng cáo và sẽ được lặp lại cho từng phần tử được cung cấp bởi đối tượng quảng cáo gốc mà ứng dụng sẽ hiển thị.
Xử lý lượt nhấp
Không triển khai bất kỳ trình xử lý lượt nhấp tuỳ chỉnh nào trên mọi chế độ xem ở trên hoặc trong chế độ xem quảng cáo gốc. SDK sẽ xử lý số lượt nhấp vào tài sản quảng cáo, chỉ cần bạn điền và đăng ký chính xác chế độ xem tài sản như đã nêu ở mục trước.
Để theo dõi lượt nhấp, hãy triển khai lệnh gọi lại lượt nhấp của SDK Quảng cáo của Google trên thiết bị di động:
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()
Đăng ký MediaView
Bạn phải sử dụng thành phần
MediaView
thay vì thành phầnImageView
nếu muốn đưa thành phần hình ảnh chính vào bố cục của quảng cáo gốc.MediaView
là mộtView
đặc biệt được thiết kế để hiển thị phần tử nghe nhìn chính, có thể là video hoặc hình ảnh.MediaView
có thể được xác định trong bố cục XML hoặc được tạo tự động. Bạn phải đặt chế độ xem này bên trong hệ phân cấp khung hiển thị củaNativeAdView
, giống như mọi khung hiển thị nội dung khác. Các ứng dụng sử dụngMediaView
phải đăng ký tài sản này vớiNativeAdView
: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
Lớp
MediaView
có thuộc tínhImageScaleType
khi hiển thị hình ảnh. Nếu bạn muốn thay đổi cách chuyển tỉ lệ hình ảnh trongMediaView
, hãy đặtImageView.ScaleType
tương ứng bằng cách sử dụng phương thứcsetImageScaleType()
củaMediaView
:Java
mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
Kotlin
mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
MediaContent
Lớp
MediaContent
chứa dữ liệu liên quan đến nội dung nghe nhìn của quảng cáo gốc. Nội dung này được hiển thị bằng cách sử dụng lớpMediaView
. Khi bạn đặt thuộc tínhMediaView
mediaContent
bằng một thực thểMediaContent
:Nếu có thành phần video, thì video đó sẽ được lưu vào vùng đệm và bắt đầu phát bên trong
MediaView
. Bạn có thể biết liệu quảng cáo có chứa thành phần video hay không bằng cách đánh dấu chọnhasVideoContent()
.Nếu quảng cáo không chứa thành phần video, thì thành phần
mainImage
sẽ được tải xuống và đặt bên trongMediaView
.
Theo mặc định,
mainImage
là thành phần hình ảnh được tải xuống đầu tiên. NếusetReturnUrlsForImageAssets(true)
được sử dụng thìmainImage
sẽ lànull
và bạn phải đặt thuộc tínhmainImage
này cho hình ảnh tải xuống theo cách thủ công. Xin lưu ý rằng hệ thống sẽ chỉ sử dụng hình ảnh này khi không có sẵn nội dung video.Đăng ký đối tượng quảng cáo gốc
Bước cuối cùng này sẽ đăng ký đối tượng quảng cáo gốc với chế độ xem chịu trách nhiệm hiển thị đối tượng đó.
Java
adView.setNativeAd(ad);
Kotlin
adView.setNativeAd(ad)
Huỷ quảng cáo
Sau khi bạn hiển thị quảng cáo gốc, hãy huỷ quảng cáo đó. Ví dụ sau đây sẽ huỷ một quảng cáo gốc:
Java
nativeAd.destroy();
Kotlin
nativeAd.destroy()
Ví dụ trên GitHub
Ví dụ về việc triển khai hoàn chỉnh quảng cáo gốc:
Các bước tiếp theo
Khám phá các chủ đề sau: