How to Add Facebook Audience Network Native Ad in Recyclerview

  • by

1) Add Dependencies

Add Facebook Ads and Recyclerview Dependencies in app level build.gradle

    //Recyclerview
    implementation "androidx.recyclerview:recyclerview:1.1.0"
    //Ads
    implementation "com.facebook.android:audience-network-sdk:5.8.0"

2) Add recyclerview to UI

Add recyclerview layout to your activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

3) Creating list_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text"
        style="@style/TextAppearance.AppCompat.Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="@string/app_name" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_launcher_foreground"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/image" />

</androidx.constraintlayout.widget.ConstraintLayout>

4) Creating Native_ad_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<com.facebook.ads.NativeAdLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:weightSum="1">

            <com.facebook.ads.MediaView
                android:id="@+id/native_ad_icon"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:contentDescription="@string/icon_desc" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.7"
                android:orientation="vertical"
                android:paddingLeft="5dp"
                android:paddingRight="5dp">

                <TextView
                    android:id="@+id/native_ad_title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:lines="1"
                    android:textColor="@android:color/black"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/native_ad_sponsored_label"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:lines="1"
                    android:textColor="@android:color/darker_gray"
                    android:textSize="12sp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/ad_choices_container"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="0.3"
                android:gravity="end"
                android:orientation="horizontal" />

        </LinearLayout>

        <com.facebook.ads.MediaView
            android:id="@+id/native_ad_media"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:contentDescription="@string/image_desc"
            android:gravity="center" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="5dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="3"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/native_ad_social_context"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:lines="1"
                    android:textColor="@android:color/darker_gray"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/native_ad_body"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ellipsize="end"
                    android:gravity="center_vertical"
                    android:lines="2"
                    android:textColor="@android:color/black"
                    android:textSize="12sp" />

            </LinearLayout>

            <Button
                android:id="@+id/native_ad_call_to_action"
                android:layout_width="100dp"
                android:layout_height="30dp"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:background="#4286F4"
                android:paddingLeft="3dp"
                android:paddingRight="3dp"
                android:textColor="@android:color/white"
                android:textSize="12sp"
                android:visibility="gone" />

        </LinearLayout>

    </LinearLayout>
</com.facebook.ads.NativeAdLayout>

5) Creating Recyclerview Adapter.


import android.app.Activity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.facebook.ads.AdOptionsView
import com.facebook.ads.NativeAd
import com.facebook.ads.NativeAdLayout
import com.facebook.ads.NativeAdsManager
import kotlinx.android.synthetic.main.list_layout.view.*
import kotlinx.android.synthetic.main.native_ad_layout.view.*

class FacebookAdsRecyclerviewAdapter(
    private val activity: Activity,
    private val list: List<String>,
    private val mNativeAdsManager: NativeAdsManager
) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    private val ITEM_VIEW_TYPE = 0
    private val AD_ITEM_VIEW_TYPE = 1
    private var mAdItems: ArrayList<NativeAd> = ArrayList()
    private val AD_DISPLAY_FREQUENCY = 5


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == AD_ITEM_VIEW_TYPE) {
            val inflate =
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.native_ad_layout, parent, false)
            NativeAdViewHolder(inflate as NativeAdLayout, activity)
        } else {
            val inflate =
                LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
            ItemViewHolder(inflate)
        }

    }

    override fun getItemCount(): Int {
        return list.size + mAdItems.size
    }

    override fun getItemViewType(position: Int): Int {
        return if (position != 0 && position % AD_DISPLAY_FREQUENCY == 0)
            AD_ITEM_VIEW_TYPE
        else
            ITEM_VIEW_TYPE
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder.itemViewType == ITEM_VIEW_TYPE) {
            val index = position - position / AD_DISPLAY_FREQUENCY
            val item = list[index]
            holder as ItemViewHolder
            item.let { holder.bind(item) }
        } else {
            try {
                Log.d("Ad Load", position.toString())
                val ad: NativeAd
                if (mAdItems.size > position / AD_DISPLAY_FREQUENCY) {
                    ad = mAdItems[position / AD_DISPLAY_FREQUENCY]
                } else {
                    ad = mNativeAdsManager.nextNativeAd()
                    if (!ad.isAdInvalidated) {
                        mAdItems.add(ad)
                    } else {
                        Log.w(
                            FacebookAdsRecyclerviewAdapter::class.java.simpleName,
                            "Ad is invalidated!"
                        )
                    }
                }
                holder as NativeAdViewHolder
                holder.bind(ad)
            } catch (e: Exception) {
                // FirebaseCrashlytics.getInstance().recordException(e)
                holder as NativeAdViewHolder
                holder.bind(null)
            }
        }
    }

    class ItemViewHolder(
        itemView: View
    ) :
        RecyclerView.ViewHolder(itemView) {
        val imageView = itemView.image
        val textView = itemView.text

        fun bind(data: String) {
            textView.text = data
        }
    }


    class NativeAdViewHolder(
        private val nativeAdLayout: NativeAdLayout,
        val context: Activity
    ) :
        RecyclerView.ViewHolder(nativeAdLayout) {

        val nativeAdIcon = nativeAdLayout.native_ad_icon
        val nativeAdTitle = nativeAdLayout.native_ad_title
        val nativeAdSponsoredLabel = nativeAdLayout.native_ad_sponsored_label
        val adChoicesContainer = nativeAdLayout.ad_choices_container
        val nativeAdMedia = nativeAdLayout.native_ad_media
        val nativeAdSocialContext = nativeAdLayout.native_ad_social_context
        val nativeAdBody = nativeAdLayout.native_ad_body
        val nativeAdCallToAction = nativeAdLayout.native_ad_call_to_action


        fun bind(ad: NativeAd?) {

            adChoicesContainer.removeAllViews()
            if (ad != null) {
                nativeAdTitle.text = ad.advertiserName
                nativeAdBody.text = ad.adBodyText
                nativeAdSocialContext.text = ad.adSocialContext
                nativeAdSponsoredLabel.text = context.getString(R.string.sponsored)
                nativeAdCallToAction.text = ad.adCallToAction
                nativeAdCallToAction.visibility = adActionButtonVisible(ad.hasCallToAction())
                val adOptionsView =
                    AdOptionsView(context, ad, nativeAdLayout)
                adChoicesContainer.addView(adOptionsView, 0)

                val clickableViews = ArrayList<View>()
                clickableViews.add(nativeAdIcon)
                clickableViews.add(nativeAdMedia)
                clickableViews.add(nativeAdCallToAction)
                ad.registerViewForInteraction(
                    nativeAdLayout,
                    nativeAdMedia,
                    nativeAdIcon,
                    clickableViews
                )

            }
        }


        private fun adActionButtonVisible(boolean: Boolean): Int {
            if (boolean)
                return View.VISIBLE
            return View.INVISIBLE
        }

    }

}

5) Adding Facebook and recyclerview code to MainActivity

class MainActivity : AppCompatActivity() {

    private lateinit var mNativeAdsManager: NativeAdsManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        AudienceNetworkAds.initialize(this)
        mNativeAdsManager =
            NativeAdsManager(this, getString(R.string.native_placement_id), 5)
        mNativeAdsManager.loadAds()

        recyclerview.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = FacebookAdsRecyclerviewAdapter(
                this@MainActivity,
                listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"),
                mNativeAdsManager
            )
        }

    }
}

Build and Run the app on the emulator or actual device. You need to add your device ID in facebook ads as test device.

Leave a Reply

Your email address will not be published. Required fields are marked *