android 如何在Jetpack Compose中强制某些屏幕的方向?

y3bcpkx1  于 2023-03-11  发布在  Android
关注(0)|答案(1)|浏览(222)

有了jetpack组合导航,我想它可能会变成一个单一活动的应用程序。如何只对某些组合(屏幕)强制方向?比如说,如果我想只在播放视频时强制横向,而不是其他屏幕?没有导航,可以在清单中声明方向,但有了导航,我们可以在组合级别指定方向?

mxg2im7a

mxg2im7a1#

您可以从LocalContext获取当前活动,然后更新requestedOrientation
要在屏幕出现时设置所需的方向,并在屏幕消失时将其恢复,请使用DisposableEffect

@Composable
fun LockScreenOrientation(orientation: Int) {
    val context = LocalContext.current
    DisposableEffect(orientation) {
        val activity = context.findActivity() ?: return@DisposableEffect onDispose {}
        val originalOrientation = activity.requestedOrientation
        activity.requestedOrientation = orientation
        onDispose {
            // restore original orientation when view disappears
            activity.requestedOrientation = originalOrientation
        }
    }
}

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

用法:

@Composable
fun Screen() {
    LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
}

相关问题