On drawing multiple Box
es on top on each other, while keeping the screen in Landscape mode, the screen flickers and the orientation changes multiple times.
Here is a reproducible example:
@Composable
fun GamePad(widthDp: Float, heightDp: Float, connectionViewModel: ConnectionViewModel?) {
LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
val deadZonePadding = heightDp / 18
Box(
modifier = Modifier
.padding(deadZonePadding.dp)
// .background(Color.Magenta)
.fillMaxSize(),
contentAlignment = Alignment.TopStart // Origin is top left
) {
}
Box(
modifier = Modifier
.padding(deadZonePadding.dp)
// .background(Color.Magenta)
.fillMaxSize(),
contentAlignment = Alignment.BottomStart // Origin is bottom left
) {
}
Box(
modifier = Modifier
.padding(deadZonePadding.dp)
// .background(Color.Magenta)
.fillMaxSize(),
contentAlignment = Alignment.TopEnd // Origin is top right
) {
}
Box(
modifier = Modifier
.padding(deadZonePadding.dp)
// .background(Color.Magenta)
.fillMaxSize(),
contentAlignment = Alignment.BottomEnd // Origin is bottom right
) {
}
}
Supporting functions from https://stackoverflow.com/a/69231996/8659747
/**
* Locks the screen orientation to the given orientation.
* @see <a href="https://stackoverflow.com/a/69231996/8659747"> StackOverflow Answer <a/>
*/
@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
}