Jetpack Compose: Get screen orientation

Introduction

In the world of Android development, screen orientation is an important aspect of user experience, particularly when designing responsive layouts for various devices. Jetpack Compose, Android's modern toolkit for building native UI, provides an efficient way to handle screen orientation changes through its composable functions. In this article, we will walk through a Kotlin example demonstrating how to get and display the screen orientation in Jetpack Compose.

The example code shows a simple yet effective method to detect screen orientation using Jetpack Compose's LocalConfiguration API. We will break down the core components, explaining how the composables and configuration states work together to reflect orientation changes in the app's UI.

Setting up the MainActivity

The code begins with the MainActivity class, which extends ComponentActivity. As the main entry point for the Android app, this class overrides the onCreate method where the Jetpack Compose UI is set up using setContent. Inside this function, the composable function GetScaffold() is called to render the app's UI. The GetScaffold() composable is responsible for structuring the basic layout using the Scaffold component, which provides a consistent layout with slots for the top app bar, content, and more.

Scaffold and AppBar Configuration

The GetScaffold() composable defines the top app bar and the main content area. A TopAppBar is used to display the app's title, "Compose - Get Screen Orientation", and is styled with a custom background color (Color(0xFF7CB9E8)). The Scaffold component simplifies organizing the overall layout of the screen, setting the foundation for both static and dynamic elements. It provides a background color and manages the main content display, which is handled by the MainContent() composable.

Displaying Screen Orientation with MainContent()

The MainContent() composable is where the core logic for detecting screen orientation resides. The LocalConfiguration.current property is used to access the current configuration of the device, which includes the screen orientation. The orientation value is stored in a variable and passed to the getOrientationName() function, which translates the orientation value (e.g., 1 for Portrait, 2 for Landscape) into a human-readable string.

To display the screen orientation, a Box composable is used to center the text on the screen. The Box fills the available screen space using the Modifier.fillMaxSize() modifier and wraps its content with Modifier.wrapContentSize(Alignment.Center). Inside the box, a Text composable is used to show the orientation information, with a large font size (30sp) and centered text alignment.

The getOrientationName() Function

The getOrientationName() function is a utility that maps the numeric orientation values retrieved from LocalConfiguration to descriptive strings. It uses a when expression to check the value of the orientation and return either "Portrait", "Landscape", "Undefined", or "Error!" depending on the input. This function plays a crucial role in making the orientation value more understandable for display purposes.

Summary

This Jetpack Compose example demonstrates how to efficiently retrieve and display screen orientation in an Android app using Kotlin. By leveraging the LocalConfiguration API within a composable function, the app dynamically updates its UI based on the device's current orientation. The use of composables like Scaffold, Box, and Text ensures a clean and maintainable UI structure that reacts to orientation changes in real-time.

Overall, this implementation showcases the simplicity and power of Jetpack Compose in building responsive and adaptive UIs for modern Android applications. As developers continue to embrace Compose, solutions like this will become increasingly valuable for crafting flexible, user-friendly apps.


MainActivity.kt

package com.cfsuman.jetpackcompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {GetScaffold()}
    }


    @Composable
    fun GetScaffold() {
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(text = "Compose - Get Screen Orientation")},
                backgroundColor = Color(0xFF7CB9E8),
            )},
            content = { MainContent() },
            backgroundColor = Color(0xFFF0FFFF)
        )
    }


    @Composable
    fun MainContent() {
        val configuration = LocalConfiguration.current
        val orientation = configuration.orientation

        Box(Modifier.fillMaxSize().wrapContentSize(Alignment.Center)) {
            Text(
                text = "Screen orientation" +
                        "\n${getOrientationName(orientation)}",
                fontSize = 30.sp,
                textAlign = TextAlign.Center
            )
        }
    }
}


fun getOrientationName(value:Int):String{
    return when (value) {
        0->{
            "Undefined"
        }
        1 -> {
            "Portrait"
        }
        2 -> {
            "Landscape"
        }
        else -> {
            "Error!"
        }
    }
}
More android jetpack compose tutorials