How to read current screen orientation on Android?

449 views Asked by At

I would like to read current screen orientation on Android using Jetpack Compose.

I already tried following in a @Composable:

val o = LocalActivity.current.requestedOrientation

val o = LocalContext.current.display.rotation

val o = LocalActivity.current.resources.configuration.orientation

but in vain.

Log.d("Orientation", "The Orientation $o")

Everytime, I rotate the orientation, log outputs on these remain the same. So they do not seem to change.

How can I read the screen orientation?

3

There are 3 answers

0
Ralf Wickum On BEST ANSWER
androidx.compose.ui.platform.LocalConfiguration.current.orientation

solved it for me.

1
F.Mysir On

You can get it from BoxWithConstraints and compare the width with the height.

A simple example:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
          //Our composable that gets the screen orientation
            BoxWithConstraints {
                val mode = remember { mutableStateOf("") }
                mode.value = if (maxWidth < maxHeight) "Portrait" else "Landscape"
                Text(text = "Now it is in ${mode.value} mode")
            }
        }
    }
}
0
zhangxaochen On

You could override onConfigurationChanged(Configuration) method of your activity.

To get this method called you also need to specify the changing in android:configChanges attribute in your manifest file.

See what and how to specify, kindly check this docs.