Skip to content

Instantly share code, notes, and snippets.

@markiyan-antonyuk
Last active September 24, 2023 09:41
Show Gist options
  • Save markiyan-antonyuk/13ff852a8a4de3c101ec21529ed5af5b to your computer and use it in GitHub Desktop.
Save markiyan-antonyuk/13ff852a8a4de3c101ec21529ed5af5b to your computer and use it in GitHub Desktop.
Composable NativeAdView
@Composable
fun NativeAdView(
ad: NativeAd,
adContent: @Composable (ad: NativeAd, contentView: View) -> Unit,
) {
val contentViewId by remember { mutableIntStateOf(View.generateViewId()) }
val adViewId by remember { mutableIntStateOf(View.generateViewId()) }
AndroidView(
factory = { context ->
val contentView = ComposeView(context).apply {
id = contentViewId
}
NativeAdView(context).apply {
id = adViewId
addView(contentView)
}
},
update = { view ->
val adView = view.findViewById<NativeAdView>(adViewId)
val contentView = view.findViewById<ComposeView>(contentViewId)
adView.setNativeAd(ad)
adView.callToActionView = contentView
contentView.setContent { adContent(ad, contentView) }
}
)
}
@Composable
fun MyAd(nativeAd: NativeAd) {
NativeAdView(ad = nativeAd) { ad, view ->
MyAdContent(ad, view)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun MyAdContent(ad: NativeAd, composeView: View) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.wrapContentHeight(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
onClick = { composeView.performClick() }
) {
ConstraintLayout(
modifier = Modifier.padding(8.dp)
) {
val (refIcon, refHeadline, refBody) = createRefs()
Box(modifier = Modifier.constrainAs(refIcon) {
start.linkTo(parent.start)
top.linkTo(parent.top)
width = Dimension.wrapContent
}) {
ad.icon?.drawable?.let { drawable ->
Box(
modifier = Modifier
.size(48.dp)
.clip(RoundedCornerShape(4.dp))
.drawWithContent {
drawIntoCanvas {
drawable.setBounds(0, 0, size.width.toInt(), size.height.toInt())
drawable.draw(it.nativeCanvas)
}
}
)
}
}
Box(modifier = Modifier.constrainAs(refHeadline) {
top.linkTo(parent.top)
start.linkTo(refIcon.end, 8.dp)
end.linkTo(parent.end)
width = Dimension.fillToConstraints
}) {
Text(
text = ad.headline.orEmpty(),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.W400
)
}
Box(modifier = Modifier.constrainAs(refBody) {
top.linkTo(refHeadline.bottom)
start.linkTo(refHeadline.start)
end.linkTo(parent.end)
width = Dimension.preferredWrapContent
}) {
Text(
text = ad.body.orEmpty(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment