Sunday, March 28, 2021

jetpack compose - Get color resource

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.res.colorResource
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(){
        Column(
            modifier = Modifier
                .background(
                    colorResource(id = R.color.layoutBackgroundColor)
                )
                .fillMaxSize()
                .padding(32.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text(
                text = "colorResource API to get colors" +
                        " from a resource XML file",
                fontSize = 40.sp,
                color = colorResource(id = R.color.defaultTextColor),
                modifier = Modifier
                    .background(
                        colorResource(id = R.color.textBackgroundColor)
                    )
                    .padding(16.dp)
            )
        }
    }


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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="layoutBackgroundColor">#FFDEA5A4</color>
    <color name="textBackgroundColor">#FFF1E9D2</color>
    <color name="defaultTextColor">#FFCC3333</color>
</resources>