Monday, March 7, 2022

jetpack compose - Detect screen orientation change

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
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.TextStyle
import androidx.compose.ui.text.font.FontWeight
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 - Detect Orientation Change")},
                backgroundColor = Color(0xFF592720),
                contentColor = Color.White
            )},
            content = { MainContent() },
            backgroundColor = Color(0xFFEEDC82)
        )
    }


    @Composable
    fun MainContent() {
        val configuration = LocalConfiguration.current
        val orientation by remember { mutableStateOf(
            when (configuration.orientation) {
                Configuration.ORIENTATION_LANDSCAPE -> {
                    "Landscape"
                }
                else -> {
                    "Portrait"
                }
            }
        )}

        Box(Modifier.fillMaxSize().wrapContentSize(Alignment.Center)) {
            Text(
                text = "Screen Orientation\n$orientation",
                style = TextStyle(
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center
                )
            )
        }
    }
}