17
votes

Is there any Orientation helpers class in Jetpack Compose, like Flutter has https://flutter.dev/docs/cookbook/design/orientation ?? I need to know when orientation have been changed to adjust my layout properly.

3

3 Answers

24
votes

We can use LocalConfiguration to listen for the orientation changes

@Composable
fun ConfigChangeExample() {
    val configuration = LocalConfiguration.current
    when (configuration.orientation) {
        Configuration.ORIENTATION_LANDSCAPE -> {
            Text("Landscape")
        }
        else -> {
            Text("Portrait")
        }
    }
}

Note: This will not help to listen to the configuration change, This will just help to get the current Configuration.

2
votes

We can use state in jectpack compose, so that a composable re-composes itself when the state changes.

An example of listening to the configuration change using state is follows:-

@Composable
fun ShowConfig(config: String) {
   Text(text = "$config!")
}

Keep a config state in activity:-

var state by mutableStateOf("Potrait")

Then listen to the config changes in the activity and on configuration just update the state by the value like:-

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        state = "Landscape" // this will automatically change the text to landscape
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        state = "Potrait"   // this will automatically change the text to potrait
    }
}

The Greeting composable observes the state of the config string whenever the state of the config string changes it re-composes.

2
votes

To observe the orientation, we can create a snapshot flow to observe changes to the orientation which feeds into a state variable you can use directly.

var orientation by remember { mutableStateOf(Configuration.ORIENTATION_PORTRAIT) }

val configuration = LocalConfiguration.current

// If our configuration changes then this will launch a new coroutine scope for it
LaunchedEffect(configuration) {
    // Save any changes to the orientation value on the configuration object
    snapshotFlow { configuration.orientation }
        .collect { orientation = it }
}

when (orientation) {
    Configuration.ORIENTATION_LANDSCAPE -> {
        LandscapeContent()
    }
    else -> {
        PortraitContent()
    }
}