Admob Collapsible Banner Ads using KOTLIN in Android Studio

Add the dependency in your app-level build.gradle.ktx file

				
					dependencies {
  implementation("com.google.android.gms:play-services-ads:23.3.0")
}
				
			

Add the dependency in your app-level build.gradle.ktx file

				
					<!--defaultConfig {-->
<!--        applicationId = "com.test.myapplication"-->
<!--        minSdk = 24-->
<!--        targetSdk = 34-->
<!--        versionCode = 1-->
<!--        versionName = "1.0"-->

<!--        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"-->
<!--    }-->
    
    buildFeatures { viewBinding = true }
    
    <!--buildTypes {-->
    <!--    release {-->
    <!--        isMinifyEnabled = false-->
    <!--        proguardFiles(-->
    <!--            getDefaultProguardFile("proguard-android-optimize.txt"),-->
    <!--            "proguard-rules.pro"-->
    <!--        )-->
    <!--    }-->
    <!--}-->
				
			

Add Dependency: Add the below code to your AndroidManifest.xml file.

				
					<manifest>
  <application>
    <!-- Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713 -->
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/> 
  </application>
</manifest>
				
			

Create a class name as ApplicationClass and enter below code : 

				
					package com.test.myapplication

import android.app.Application
import com.google.android.gms.ads.MobileAds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class ApplicationClass : Application(){
    override fun onCreate() {
        super.onCreate()

        val backgroundScope = CoroutineScope(Dispatchers.IO)
        backgroundScope.launch {
            // Initialize the Google Mobile Ads SDK on a background thread.
            MobileAds.initialize(this@ApplicationClass) {}
        }
    }
}
				
			

Create a class name as AdManager and enter below code : 

				
					package com.test.myapplication

import android.app.Activity
import android.content.Context
import android.os.Build
import android.view.WindowMetrics
import android.widget.LinearLayout
import android.widget.Toast
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.LoadAdError
class AdManager(private val context: Context, private val adContainer: LinearLayout) {
    private lateinit var adView: AdView

    // Get the ad size with screen width.
    private val adSize: AdSize
        get() {
            val displayMetrics = context.resources.displayMetrics
            val adWidthPixels =
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    val windowMetrics: WindowMetrics =
                        (context as? Activity)?.windowManager?.currentWindowMetrics
                            ?: return AdSize.BANNER
                    windowMetrics.bounds.width()
                } else {
                    displayMetrics.widthPixels
                }
            val density = displayMetrics.density
            val adWidth = (adWidthPixels / density).toInt()
            return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidth)
        }
    fun showBannerAd() {
        // Create a new ad view.
        val adView = AdView(context)
        adView.adUnitId = "ca-app-pub-3940256099942544/9214589741"
        adView.setAdSize(adSize)
        this.adView = adView
        // Replace ad container with new ad view.
        adContainer.removeAllViews()
        adContainer.addView(adView)
        // Start loading the ad in the background.
        val adRequest = AdRequest.Builder().build()
        adView.loadAd(adRequest)
        adView.adListener = object : AdListener() {
            override fun onAdFailedToLoad(adError: LoadAdError) {
                // Code to be executed when an ad request fails.
                Toast.makeText(context, "Banner Ads Loading Failed", Toast.LENGTH_SHORT).show()
            }
            override fun onAdLoaded() {
                // Code to be executed when an ad finishes loading.
                Toast.makeText(context, "Banner Ads Loaded", Toast.LENGTH_SHORT).show()
            }
        }
    }
}
				
			

Enter the below code in 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Collapsible Banner Ad"
        android:textSize="25sp"
        app:layout_constraintBottom_toTopOf="@+id/adContainer"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/adContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
				
			

Enter the below code in MainActivity.kt : 

				
					package com.test.myapplication

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    // Get the ad size with screen width.
    private lateinit var adManager: AdManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        adManager = AdManager(this, findViewById(R.id.adContainer))
        adManager.showBannerAd()

    }
}
				
			

Then, you can just run your app on an android device.

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping