How to disable landscape mode for a composable function? I want to show the composable in portrait mode always.
PS: Cannot set it in manifest file for the activity since I want this behaviour for one composable only and not others in the activity.
How to disable landscape mode for a composable function? I want to show the composable in portrait mode always.
PS: Cannot set it in manifest file for the activity since I want this behaviour for one composable only and not others in the activity.
You can do this with 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
}
Usage:
@Composable
fun Screen() {
LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
}