This is the composable holding Lazycolumn and after every 5th item native ad has been visible but due to lazycolumn recomposition when I'm scrolling ads got disappeared and after coming back ads again reappearing.
@Preview
@Composable
fun TestingScreen() {
LazyColumnWithBoxesAndText()
}
This is the composable holding Lazycolumn and after every 5th item native ad has been placed but due to lazycolumn recomposition happening
@Composable
fun LazyColumnWithBoxesAndText() {
val colors by remember {
mutableStateOf(generateRandomColors(100))
}
LazyColumn {
items(100) { index ->
Text(
text = "Item $index",
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
if ((index + 1) % 5 == 0 && index != 0) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(50.dp)
.padding(16.dp)
.background(colors[index])
)
ApplovinNativeSmallAd()
}
}
}
}
fun generateRandomColors(count: Int): List<Color> {
val random = Random(System.currentTimeMillis())
return List(count) {
Color(random.nextFloat(), random.nextFloat(), random.nextFloat(), 1f)
}
}
This is my Native Ad View
@Composable
fun ApplovinNativeSmallAd() {
val context = LocalContext.current
val nativeAdLoader = remember { MaxNativeAdLoader("xxxxxxxxxxxxxx", context) }
val nativeAdContainer = remember { mutableStateOf<FrameLayout?>(null) }
var nativeAd by remember { mutableStateOf<MaxAd?>(null) }
DisposableEffect(Unit) {
val container = FrameLayout(context)
nativeAdContainer.value = container
onDispose {
nativeAdContainer.value = null
}
}
val container = nativeAdContainer.value
if (container != null) {
AndroidView(
modifier = Modifier
.fillMaxWidth()
.background(Color.Black),
factory = {
nativeAdLoader.setNativeAdListener(object : MaxNativeAdListener() {
override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, ad: MaxAd) {
nativeAd?.let {
nativeAdLoader.destroy(it)
}
nativeAd = ad
container.removeAllViews()
container.addView(nativeAdView)
}
override fun onNativeAdLoadFailed(adUnitId: String, error: MaxError) {
}
override fun onNativeAdClicked(ad: MaxAd) {
}
})
nativeAdLoader.loadAd()
container
}
)
}
}