Sunday, March 28, 2021

jetpack compose - String resource plurals

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        val resources = LocalContext.current.resources

        Column(
            modifier = Modifier
                .background(Color(0xFFE1A95F))
                .fillMaxSize()
                .padding(32.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = resources.getQuantityString(
                    R.plurals.runtime_format,
                    1,
                    1
                ),
                fontSize = 40.sp,
                color = Color(0xFF563C5C),
            )

            Text(
                text = resources.getQuantityString(
                    R.plurals.runtime_format,
                    5,
                    5
                ),
                fontSize = 40.sp,
                color = Color(0xFF563C5C),
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}
res/values/strings.xml

<resources>
    <string name="app_name">Compose - String Resource Plurals</string>

    <plurals name="runtime_format">
        <item quantity="one">%1$d minute</item>
        <item quantity="other">%1$d minutes</item>
    </plurals>
</resources>