1

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?

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103
  • 2
    "Everytime, I rotate the orientation, log outputs on these remain the same" -- you might want to expand your [mcve] to show when and how you are logging these values. Beyond that, though, bear in mind that with split screen, freeform multi-window (Chrome OS, Samsung DeX, etc.), foldables, and the changes coming in Android 12L, that "orientation" is becoming an obsolete concept. – CommonsWare Nov 29 '21 at 00:46

3 Answers3

0

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.

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

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")
            }
        }
    }
}
F.Mysir
  • 2,838
  • 28
  • 39
  • orientation is not just Portrait or Landscape. It can be 0, 90, 180, 270 degree rotation. There any way to determine the degree? – Tapa Save Oct 03 '22 at 03:08
0
androidx.compose.ui.platform.LocalConfiguration.current.orientation

solved it for me.

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103