ITmob-Ly
发布于 2023-08-23 / 164 阅读
0

Jetpack Compose 中如何在 Composable 可组合函数中获取 Activity 的 Window 属性?

介绍

前文介绍了在 Jetpack Compose 的可组合函数中怎样获取 Activity,这里就顺便水一篇怎样获取 Activity 的 Window 属性。本文纯属水文备忘,如果已经看了前文,获取了 Activity 再获取它的属性就很简单了。

代码:

获取 Activity 的 window 属性,并显示出 window 对象的属性信息

@Composable
fun WindowPropertySample() {
    val window = LocalContext.current.findActivity().window
    Text(text = "https://itmob.cn", color = Color.Red)
    Spacer(modifier = Modifier.size(16.dp))
    Text(text = "window attributes: \n${window.attributes}")
}

internal fun Context.findActivity(): Activity {
    var context = this
    while (context is ContextWrapper) {
        if (context is Activity) return context
        context = context.baseContext
    }
    throw IllegalStateException("Permissions should be called in the context of an Activity")
}

Get window attributes from composable function