Issue
I need to call this function to show an interstitial ad from a button click inside a composable function, which expects an activity for the show() method:
fun showInterstitial() {
if (mInterstitialAd != null) {
mInterstitialAd?.show(this)
} else {
Log.d("MainActivity", "The interstitial ad wasn't ready yet.")
}
}
How can I get the current activity and replace the this part?
Thanks for your answer!
Solution
You can get current context using LocalContext. With Compose usually it's gonna be your activity already, but to be sure you can unwrap it like this:
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
}
If you need to use context inside your view model, or in an other place where your handler function is located, you can pass context to your handler function.
fun showInterstitial(context: Context) {
val activity = context.findActivity()
}
@Composable
fun View() {
val context = LocalContext.current
Button(onClick = {
showInterstitial(context)
}) {
}
}
Answered By - Philip Dukhov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.