본문 바로가기
코드

Android 적응형 배너 적용

by umaking 2022. 8. 7.

Gradle 7.2.2에서 viewBinding 적용과 적응형 배너 적용 source.

 

build.gradle

plugins {
    // 추가
    id 'kotlin-parcelize'
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout ~~~~~~~~>

    <FrameLayout
        android:id="@+id/ad_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_alignParentBottom="true" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.kt

private lateinit var binding: ActivityMainBinding
private lateinit var adView: AdView
private var initialLayoutComplete = false

private val adSize: AdSize
    get() {
        val outMetrics = Resources.getSystem().displayMetrics
        val density = outMetrics.density

        var adWidthPixels = binding.adViewContainer.width.toFloat()
        if (adWidthPixels == 0f) {
            adWidthPixels = outMetrics.widthPixels.toFloat()
        }

        val adWidth = (adWidthPixels / density).toInt()
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth)
    }

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
//        setContentView(R.layout.activity_main)

    MobileAds.initialize(this) {}

    // 테스트 Device ID
//        MobileAds.setRequestConfiguration(
//            RequestConfiguration.Builder().setTestDeviceIds(listOf("ABCDEF012345")).build()
//        )

    adView = AdView(this)

    binding.adViewContainer.addView(adView)
    binding.adViewContainer.viewTreeObserver.addOnGlobalLayoutListener {
        if (!initialLayoutComplete) {
            initialLayoutComplete = true
            loadBanner()
        }
    }
}

private fun loadBanner() {
    adView.adUnitId = AD_UNIT_ID
    adView.setAdSize(adSize)

    val adRequest = AdRequest.Builder().build()

    adView.loadAd(adRequest)
}

companion object {
    private val AD_UNIT_ID = "ca-app-pub-~~~~~~~~~"
}

 

끝.

 

'코드' 카테고리의 다른 글

inline code  (0) 2023.11.17
keyscan  (0) 2023.11.17
Android viewBinding로 변경  (0) 2022.08.07
iOS에서 admob의 SKAdNetwork적용 후 앱 승인요청 필요 정보.  (0) 2021.06.01
Datagrip에서 dbms_output 출력하기  (1) 2021.04.03