gpt4 book ai didi

android - 如何从可组合函数中获取当前 Activity ?

转载 作者:行者123 更新时间:2023-12-04 23:46:41 25 4
gpt4 key购买 nike

我需要调用此函数以通过可组合函数内的按钮单击显示插页式广告,该函数需要 show() 的 Activity 方法:

fun showInterstitial() {
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
} else {
Log.d("MainActivity", "The interstitial ad wasn't ready yet.")
}
}
如何获取当前 Activity 并替换 this部分?
感谢您的回答!

最佳答案

您可以使用 LocalContext 获取当前上下文.使用 Compose 通常它已经是你的 Activity 了,但要确保你可以像这样打开它:

fun showInterstitial(context: Context) {
val activity = context.findActivity()
}

@Composable
fun View() {
val context = LocalContext.current
Button(onClick = {
val activity = context.findActivity()
}) {

}
}

fun Context.findActivity(): AppCompatActivity? = when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.findActivity()
else -> null
}

如果您需要在 View 模型内或处理函数所在的其他位置使用上下文,您可以将上下文传递给处理函数。
fun showInterstitial(context: Context) {
val activity = context.findActivity()
}

@Composable
fun View() {
val context = LocalContext.current
Button(onClick = {
showInterstitial(context)
}) {

}
}

关于android - 如何从可组合函数中获取当前 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69044733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com