如何从可组合函数获取当前活动?

Raw*_*san 8 android kotlin android-jetpack-compose

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

fun showInterstitial() {
    if (mInterstitialAd != null) {
        mInterstitialAd?.show(this)
    } else {
        Log.d("MainActivity", "The interstitial ad wasn't ready yet.")
    }
}
Run Code Online (Sandbox Code Playgroud)

如何获取当前活动并更换零件this

感谢您的回答!

Phi*_*hov 17

您可以使用 获取当前上下文LocalContext。使用 Compose,通常它已经是您的活动了,但为了确保您可以像这样展开它:

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
}
Run Code Online (Sandbox Code Playgroud)

如果您需要在视图模型内或处理程序函数所在的其他位置使用上下文,则可以将上下文传递给处理程序函数。

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

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

    }
}
Run Code Online (Sandbox Code Playgroud)