Sunday, March 6, 2022

jetpack compose - Get primary language

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.os.Build
import android.os.Bundle
import android.os.LocaleList
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
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.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp


class MainActivity : ComponentActivity() {
    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {GetScaffold()}
    }


    @RequiresApi(Build.VERSION_CODES.N)
    @Composable
    fun GetScaffold() {
        Scaffold(
            topBar = {TopAppBar(
                title = {Text(text = "Compose - Get Primary Language")},
                backgroundColor = Color(0xFF7CB9E8),
            )},
            content = { MainContent() },
            backgroundColor = Color(0xFFF0FFFF)
        )
    }


    @RequiresApi(Build.VERSION_CODES.N)
    @Composable
    fun MainContent() {
        val configuration = LocalConfiguration.current
        val locales:LocaleList = configuration.locales

        Column(Modifier.padding(12.dp)) {
            Text(
                text = "Display Language : ${locales.get(0).displayLanguage}",
                fontSize = 20.sp
            )
            Text(
                text = "Country : ${locales.get(0).country}",
                fontSize = 20.sp
            )
            Text(
                text = "Display Name : ${locales.get(0).displayName}",
                fontSize = 20.sp
            )
            Text(
                text = "Language : ${locales.get(0).language}",
                fontSize = 20.sp
            )
        }
    }
}