如何在撰写中获得活动 [英] How to get activity in compose

查看:22
本文介绍了如何在撰写中获得活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 compose 函数中获取当前活动?

Is there a way to get current activity in compose function?

@Composable
fun CameraPreviewScreen() {
    val context = ContextAmbient.current
    if (ActivityCompat.checkSelfPermission(
            context,
            Manifest.permission.CAMERA
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        ActivityCompat.requestPermissions(
            this, MainActivity.REQUIRED_PERMISSIONS, MainActivity.REQUEST_CODE_PERMISSIONS  // get activity for `this`
        )
        return
    }
}

推荐答案

虽然上一个答案(ContextWrapper-aware)确实是正确的,我想提供一个更惯用的实现来复制粘贴.

While the previous answer (which is ContextWrapper-aware) is indeed the correct one, I'd like to provide a more idiomatic implementation to copy-paste.

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

由于 ContextWrapper 不可能相互包裹显着 次,因此递归在这里很好.

As ContextWrappers can't possibly wrap each other significant number of times, recursion is fine here.

这篇关于如何在撰写中获得活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆