Created
December 6, 2023 20:26
-
-
Save LethalMaus/54d53e499634b5081a0f4d9e9f069184 to your computer and use it in GitHub Desktop.
admob2.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fun setupBanner(adContainerView: FrameLayout) { | |
| adView = AdView(requireContext()) | |
| adContainerView.addView(adView) | |
| adContainerView.viewTreeObserver.addOnGlobalLayoutListener { | |
| if (!initialLayoutComplete) { | |
| initialLayoutComplete = true | |
| loadBanner(adContainerView) | |
| } | |
| } | |
| } | |
| private fun loadBanner(adContainerView: FrameLayout) { | |
| adView.adUnitId = BuildConfig.AD_MOB_BANNER | |
| adView.setAdSize(getAdSize(adContainerView)) | |
| adView.loadAd(AdRequest.Builder().build()) | |
| } | |
| private fun getAdSize(adContainerView: FrameLayout): AdSize { | |
| val width = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { | |
| val windowMetrics = requireActivity().windowManager.currentWindowMetrics | |
| windowMetrics.bounds.width().toFloat() | |
| } else { | |
| val displayMetrics = DisplayMetrics() | |
| requireActivity().windowManager.defaultDisplay.getMetrics(displayMetrics) | |
| displayMetrics.widthPixels.toFloat() | |
| } | |
| var adWidthPixels = adContainerView.width.toFloat() | |
| if (adWidthPixels == 0f) { | |
| adWidthPixels = width | |
| } | |
| val density = resources.displayMetrics.density | |
| val adWidth = (adWidthPixels / density).toInt() | |
| return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), adWidth) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment