简体   繁体   English

Jetpack Compose 在 Android 视图中更新广告横幅

[英]Jetpack Compose update ad banner in Android View

In Jetpack Compose I'm using AndroidView to display an ad banner from a company called Smart.IO.在 Jetpack Compose 中,我使用AndroidView显示来自一家名为 Smart.IO 的公司的广告横幅。

At the moment the banner shows when first initialised, but then fails to recompose when user comes back to the screen it's displayed on.目前,横幅在首次初始化时显示,但当用户返回显示它的屏幕时无法重新组合。

I'm aware of using the update function inside compose view, but I can't find any parameters I could use to essentially update on Banner to trigger the recomposition.我知道在 compose 视图中使用update函数,但是我找不到任何可以用来基本上更新Banner以触​​发重组的参数。

AndroidView(
    modifier = Modifier
        .fillMaxWidth(),
    factory = { context ->
        Banner(context as Activity?)
    },
    update = {
        
    }
)

This could be a library error.这可能是库错误。 You can check if this view behaves normally in normal Android XML.您可以检查此视图在普通 Android XML 中的行为是否正常。

Or maybe you need to use some API from this library, personally I haven't found any decent documentation or Android SDK source code.或者你可能需要使用这个库中的一些 API,我个人还没有找到任何像样的文档或 Android SDK 源代码。


Anyway, here is how you can make your view update.无论如何,这是您可以更新视图的方法。

You can keep track of life-cycle events, as shown in this answer , and only display your view during ON_RESUME .您可以跟踪生命周期事件,如本答案所示,并且仅在ON_RESUME期间显示您的视图。 This will take it off the screen when it is paused, and make it create a new view when it resumes:这将在暂停时将其从屏幕上移开,并在恢复时创建一个新视图:

val lifeCycleState by LocalLifecycleOwner.current.lifecycle.observeAsSate()
if (lifeCycleState == Lifecycle.Event.ON_RESUME) {
    AndroidView(
        modifier = Modifier
            .fillMaxWidth(),
        factory = { context ->
            Banner(context as Activity?)
        },
        update = {

        }
    )
}

Lifecycle.observeAsSate : Lifecycle.observeAsSate

@Composable
fun Lifecycle.observeAsSate(): State<Lifecycle.Event> {
    val state = remember { mutableStateOf(Lifecycle.Event.ON_ANY) }
    DisposableEffect(this) {
        val observer = LifecycleEventObserver { _, event ->
            state.value = event
        }
        this@observeAsSate.addObserver(observer)
        onDispose {
            this@observeAsSate.removeObserver(observer)
        }
    }
    return state
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM