เนทีฟขั้นสูง

เลือกแพลตฟอร์ม Android iOS

แสดง NativeAd

เมื่อโฆษณาเนทีฟโหลด SDK โฆษณาในอุปกรณ์เคลื่อนที่ของ Google จะเรียกใช้ Listener สําหรับรูปแบบโฆษณาที่เกี่ยวข้อง จากนั้นแอปของคุณจะต้องรับผิดชอบในการแสดงโฆษณา แม้ว่าจะไม่จำเป็นต้องแสดงทันที SDK มีแหล่งข้อมูลที่เป็นประโยชน์ดังที่อธิบายไว้ด้านล่างเพื่อช่วยให้คุณแสดงโฆษณารูปแบบที่ระบบกําหนดได้ง่ายขึ้น

กำหนดคลาส NativeAdView

กำหนดคลาส NativeAdView คลาสนี้เป็นคลาส ViewGroup และเป็นคอนเทนเนอร์ระดับบนสุดของคลาส NativeAdView การแสดงโฆษณาเนทีฟแต่ละรายการมีชิ้นงานโฆษณาเนทีฟ เช่น เอลิเมนต์มุมมอง MediaView หรือเอลิเมนต์มุมมอง Title ซึ่งต้องเป็นองค์ประกอบย่อยของออบเจ็กต์ NativeAdView

เลย์เอาต์ XML

วิธีเพิ่ม XML NativeAdView ลงในโปรเจ็กต์

<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

รวมโมดูล JetpackComposeDemo/compose-util ซึ่งมีตัวช่วยสำหรับคอมโพสิชัน NativeAdView และชิ้นงานของ NativeAdView

เขียน NativeAdView โดยใช้ข้อบังคับ compose-util

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

จัดการ aad เนทีฟที่โหลด

เมื่อโฆษณาเนทีฟโหลด ให้จัดการเหตุการณ์ Callback, ขยายการแสดงโฆษณาเนทีฟ และเพิ่มลงในลําดับชั้นของมุมมอง ดังนี้

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())
}

โปรดทราบว่าชิ้นงานทั้งหมดสําหรับโฆษณาเนทีฟหนึ่งๆ ควรแสดงผลภายในเลย์เอาต์ NativeAdView Google Mobile Ads SDK จะพยายามบันทึกคําเตือนเมื่อแสดงผลชิ้นงานเนทีฟนอกเลย์เอาต์การแสดงโฆษณาเนทีฟ

คลาสมุมมองโฆษณายังมีเมธอดที่ใช้ลงทะเบียนมุมมองที่ใช้สำหรับแต่ละชิ้นงาน และอีกเมธอดหนึ่งสำหรับลงทะเบียนออบเจ็กต์ NativeAd เอง การลงทะเบียนมุมมองด้วยวิธีนี้จะช่วยให้ SDK จัดการงานต่างๆ โดยอัตโนมัติได้ เช่น

  • การคลิกที่บันทึกไว้
  • การบันทึกการแสดงผลเมื่อมองเห็นพิกเซลแรกบนหน้าจอ
  • การแสดงการวางซ้อน "ตัวเลือกโฆษณาอื่นๆ"

การวางซ้อน "ตัวเลือกโฆษณาอื่นๆ"

SDK จะเพิ่มการวางซ้อน "ตัวเลือกโฆษณาอื่นๆ" ลงในมุมมองโฆษณาแต่ละรายการ เว้นพื้นที่ไว้ที่มุมที่ต้องการของมุมมองโฆษณาเนทีฟสําหรับโลโก้ตัวเลือกโฆษณาอื่นๆ ที่แทรกโดยอัตโนมัติ นอกจากนี้ สิ่งสำคัญคือการวางซ้อน "ตัวเลือกโฆษณาอื่นๆ" ต้องสังเกตเห็นได้ง่าย ดังนั้นให้เลือกสีและภาพพื้นหลังอย่างเหมาะสม ดูข้อมูลเพิ่มเติมเกี่ยวกับลักษณะและฟังก์ชันของการวางซ้อนได้ที่คำอธิบายช่องโฆษณาเนทีฟ

การระบุแหล่งที่มาของโฆษณา

คุณต้องแสดงการระบุแหล่งที่มาของโฆษณาเพื่อระบุว่าการดูดังกล่าวเป็นโฆษณา ดูข้อมูลเพิ่มเติมในหลักเกณฑ์ของนโยบาย

ตัวอย่างโค้ด

ขั้นตอนในการแสดงโฆษณาเนทีฟมีดังนี้

  1. สร้างอินสแตนซ์ของคลาส NativeAdView
  2. ชิ้นงานโฆษณาแต่ละรายการที่จะแสดงต้องมีคุณสมบัติดังต่อไปนี้

    1. ป้อนข้อมูลชิ้นงานในมุมมองชิ้นงานด้วยชิ้นงานในแอบเจ็กต์โฆษณา
    2. ลงทะเบียนมุมมองเนื้อหากับคลาส NativeAdView
  3. ลงทะเบียน MediaView หากเลย์เอาต์โฆษณาเนทีฟมีชิ้นงานสื่อขนาดใหญ่

  4. ลงทะเบียนออบเจ็กต์โฆษณากับคลาส NativeAdView

ตัวอย่างฟังก์ชันที่แสดง 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) }
          }
        }
      }
    }
  }
}

แต่ละงานมีดังนี้

  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 ที่มีอยู่ซ้ำได้หากมีในฟragment หรือกิจกรรม หรือแม้แต่สร้างอินสแตนซ์แบบไดนามิกโดยไม่ต้องใช้ไฟล์เลย์เอาต์

  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 จะจัดการการคลิกชิ้นงานมุมมองโฆษณา ตราบใดที่คุณป้อนข้อมูลและลงทะเบียนมุมมองชิ้นงานอย่างถูกต้องตามที่ได้อธิบายไว้ในส่วนก่อนหน้า

    หากต้องการรอฟังการคลิก ให้ใช้การเรียกกลับการคลิกของ Google Mobile Ads SDK โดยทำดังนี้

    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. ลงทะเบียน MediaView

    คุณต้องใช้ชิ้นงาน MediaView แทนชิ้นงาน ImageView หากต้องการรวมชิ้นงานรูปภาพหลักไว้ในเลย์เอาต์ของโฆษณาเนทีฟ

    MediaView คือ View พิเศษที่ออกแบบมาเพื่อแสดงชิ้นงานสื่อหลัก ไม่ว่าจะเป็นวิดีโอหรือรูปภาพ

    MediaView สามารถกําหนดได้ในเลย์เอาต์ XML หรือสร้างแบบไดนามิก ชิ้นงานนี้ควรอยู่ในลําดับชั้นมุมมองของ NativeAdView เช่นเดียวกับมุมมองชิ้นงานอื่นๆ แอปที่ใช้ MediaView ต้องลงทะเบียน MediaView กับ 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

    คลาส MediaView มีพร็อพเพอร์ตี้ ImageScaleType เมื่อแสดงรูปภาพ หากต้องการเปลี่ยนวิธีปรับขนาดรูปภาพใน MediaView ให้ตั้งค่า ImageView.ScaleType ที่เกี่ยวข้องโดยใช้เมธอด setImageScaleType() ของ MediaView ดังนี้

    Java

    mediaView.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
    

    Kotlin

    mediaView.imageScaleType = ImageView.ScaleType.CENTER_CROP
    

    MediaContent

    คลาส MediaContent จะเก็บข้อมูลที่เกี่ยวข้องกับเนื้อหาสื่อของโฆษณาเนทีฟ ซึ่งแสดงโดยใช้คลาส MediaView เมื่อตั้งค่าพร็อพเพอร์ตี้ MediaView mediaContent ด้วยอินสแตนซ์ MediaContent

    • หากชิ้นงานวิดีโอพร้อมใช้งาน ระบบจะบัฟเฟอร์และเริ่มเล่นชิ้นงานภายในMediaView คุณดูได้ว่าชิ้นงานวิดีโอพร้อมใช้งานหรือไม่โดยตรวจสอบ hasVideoContent()

    • หากโฆษณาไม่มีชิ้นงานวิดีโอ ระบบจะดาวน์โหลดชิ้นงาน mainImage และวางไว้ภายใน MediaView แทน

    โดยค่าเริ่มต้น mainImage คือชิ้นงานรูปภาพที่ดาวน์โหลดรายการแรก หากใช้ setReturnUrlsForImageAssets(true) mainImage คือ null และคุณต้องตั้งค่าพร็อพเพอร์ตี้ mainImage เป็นรูปภาพที่ดาวน์โหลดด้วยตนเอง โปรดทราบว่าระบบจะใช้รูปภาพนี้เมื่อไม่มีชิ้นงานวิดีโอเท่านั้น

  5. ลงทะเบียนออบเจ็กต์โฆษณาเนทีฟ

    ขั้นตอนสุดท้ายนี้จะลงทะเบียนออบเจ็กต์โฆษณาเนทีฟกับมุมมองที่รับผิดชอบในการแสดงโฆษณา

    Java

    adView.setNativeAd(ad);
    

    Kotlin

    adView.setNativeAd(ad)
    

ทำลายโฆษณา

เมื่อแสดงโฆษณาเนทีฟเสร็จแล้ว คุณควรทำลายโฆษณาเพื่อให้ระบบรวบรวมขยะอย่างเหมาะสม

Java

nativeAd.destroy();

Kotlin

nativeAd.destroy()

ตัวอย่างใน GitHub

ตัวอย่างการติดตั้งใช้งานโฆษณาเนทีฟที่สมบูรณ์

Java Kotlin JetpackCompose

ขั้นตอนถัดไป

สำรวจหัวข้อต่อไปนี้