Display native ad on Android

Step 1: Layout the native ad in xml

The types of views that can be configured in a native ad are as follows:

  • Icon

  • Advertiser

  • Headline

  • Body

  • Media

  • Call to action

For example, when configuring a social feed ad, you can lay it out as follows:

<io.adrop.ads.nativeAd.AdropNativeAdView
    android:id="@+id/adrop_native_ad_view"
    ...>
    <LinearLayout
        android:orientation="horizontal"
        ... >
          <ImageView
           android:id="@+id/ad_icon"
           ... />
          <TextView
            android:id="@+id/ad_advertiser"
            ... />
     </LinearLayout>

   <io.adrop.ads.nativeAd.AdropMediaView
       android:id="@+id/ad_media"
       ... />
    
    <TextView
        android:id="@+id/ad_body"
        ... />
</LinearLayout>

Step 2: Load a native ad

val nativeAd = AdropNativeAd(context, "YOUR_UNIT_ID")
nativeAd.listener = object: AdropNativeAdListener {
    override fun onAdReceived(ad: AdropNativeAd) {
        Log.d("Adrop", "AdropNativeAd receive")
        populateNativeAdView(ad)
    }
    
    override fun onAdFailedToReceive(ad: AdropNativeAd, errorCode: AdropErrorCode) {
        Log.d("Adrop", "AdropNativeAd failed to receive $errorCode")
    }
    
    override fun onAdClicked(ad: AdropNativeAd) {
        Log.d("Adrop", "AdropNativeAd clicked")
    }
}
nativeAd.load()

Step 3: Connect a native ad to view

Here is an example that creates a AdropNativeAdView and populates it with a AdropNativeAd:

val adView: AdropNativeAdView = findViewById(R.id.adrop_native_ad_view)

fun populateNativeAdView(ad; AdropNativeAd) {
    adView.setIconView(findViewById(R.id.ad_icon))
    adView.setAdvertiserView(findViewById(R.id.ad_advertiser))
    adView.setBodyView(findViewById(R.id.ad_body))
    adView.setMediaView(findViewById(R.id.ad_media))
    ...
    
    // Call the AdropNativeAdView's setNativeAd method to register the
    // AdropNativeAd.
    adView.setNativeAd(ad)
    
    ...
}

Destroy

When you are done showing your AdropNativeAd, you should destroy it so that the ad is properly garbage collected.

nativeAd.destroy()
adView.destroy()

Last updated