Adding an ad to a Fragment (KOTLIN)

Issue

I hope you have been having a good day so far! I am trying to add and ad to my fragment but it keeps not showing when I run the program (KOTLIN).

Here is my fragment XML (running the tester ad):

    <com.google.android.gms.ads.AdView
    xmlns:ads"http://schemas.android.com/apk/res-auto"
    android:id"@+id/adView"
    android:layout_marginTop"450dp"
    android:elevation"7dp"
    android:layout_width"wrap_content"
    android:layout_height"wrap_content"
    ads:adSize"SMART_BANNER"
    ads:adUnitId"ca-app-pub-3940256099942544/6300978111">

</com.google.android.gms.ads.AdView>

Then I am trying to load it in my fragment here (SettingsFragment.kt):

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    _binding  FragmentSettingsBinding.inflate(inflater, container, false)
    val view  binding.root
    return view

    MobileAds.initialize(context)
    val adRequest  AdRequest.Builder().build()
    binding.adView.loadAd(adRequest)
}

My Build.gradle has these two lines in them:

implementation 'com.google.android.gms:play-services-ads:19.3.0'
implementation 'com.android.support:multidex:1.0.3'

And I think my android manifest is also in order with meta-data and internet permission (the value is changed)

    <meta-data
    android:name"com.google.android.gms.ads.APPLICATION_ID"
    android:value"ca-app-pub-1234567890123456~1234567890"/>

    <uses-permission android:name"android.permission.INTERNET" />

I’ve been searching all over but haven’t found anywhere to help me put an ad in a fragment. Has anyone done this before/know how to do it? I’m new to android and don’t know how to do to many things yet. Thank you so much!

Solution

All I had to do was move my creating mobile ads into the OnViewCreated() section:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    MobileAds.initialize(context) {}
    mAdView  binding.adView
    val adRequest  AdRequest.Builder().build()
    mAdView.loadAd(adRequest)
}

I am sincerely sorry for wasting the people’s time who looked at my question’s time, and I am very appreciative of their caring nature. Thank you very much!

Answered By – Casper Stockman

Leave a Comment