Skip to content

Instantly share code, notes, and snippets.

@anoop4real
Created August 13, 2018 06:27
Show Gist options
  • Select an option

  • Save anoop4real/853887d725d4fd1baab2bda9d4b31825 to your computer and use it in GitHub Desktop.

Select an option

Save anoop4real/853887d725d4fd1baab2bda9d4b31825 to your computer and use it in GitHub Desktop.
Admob: Add Banner view programatically in Kotlin
fun createLayout(){
// Get the layout from xml
val layout: ConstraintLayout = admob_contraint_layout
val cs = ConstraintSet()
// Create layout params for content size
var params : ConstraintLayout.LayoutParams = ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT
)
// Create AdView
var adView = AdView(this)
// Set Ad Size
adView.setAdSize(AdSize.BANNER);
// Set Ad Unit Id
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
// Generate a View Id
adView.id = View.generateViewId()
// Set the size params
adView.layoutParams = params
// Add it to the layout
layout.addView(adView)
// Create ConstraintSet
cs.clone(layout)
// Bottom of the banner to bottom of parent, 16dp
cs.connect(adView.id, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 16)
// Center it horizontally with the parent.
cs.centerHorizontally(adView.id, ConstraintSet.PARENT_ID)
// Set horizontal bias
cs.setHorizontalBias(adView.id,0.5f)
// Since the height is already set, these constraints would be enough to
// keep the banner to the bottom of the page. Apply the constraints to the layout
cs.applyTo(layout)
mAdView = adView
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment