在撰写中禁用横向模式

And*_*mer 6 android android-jetpack-compose

如何禁用可组合函数的横向模式?我想始终以纵向模式显示可组合项。

PS:无法在活动的清单文件中设置它,因为我只希望此行为适用于一个可组合项,而不适用于活动中的其他可组合项。

Phi*_*hov 12

您可以使用DisposableEffect+ Activity来做到这一点requestedOrientation

@Composable
fun LockScreenOrientation(orientation: Int) {
    val context = LocalContext.current
    DisposableEffect(Unit) {
        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
}
Run Code Online (Sandbox Code Playgroud)

用法:

@Composable
fun Screen() {
    LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
}
Run Code Online (Sandbox Code Playgroud)